首页 > 解决方案 > React 应用无法导入使用 webpack 打包的 react 应用

问题描述

我有一个反应应用程序,我向其中导入了另一个名为react-lex-plus 的反应项目。我管理这两个项目。

当我构建 react-lex-plus 时,webpack 能够捆绑我的应用程序。但是,当我将它导入我的主应用程序时,它会抛出一个错误,说“require is undefined”。

有谁知道为什么会发生这种情况?为什么没有定义require?

我做了以下事情:

  1. 确保 react-lex-plus 的 webpack.config.js 具有“externals”属性,其值为“commonjs react”

  2. 从 react-lex-plus 中删除 react 并将其链接到我的主项目中的 react 库。

  3. 从主项目中取消 react 并在 react-lex-plus 中安装 react。

以下是来自浏览器的错误消息。

ReferenceError: require is not defined
eval
./external_%22react%22?:1:18
react
/Users/xxxxxxxx/dev/react-lex-plus/build/index.js:3360
  3357 | /*! no static exports found */
  3358 | /***/ (function(module, exports) {
  3359 | 
> 3360 | eval("module.exports = require(\"react\");\n\n//# sourceURL=webpack:///external_%22react%22?");
  3361 | 
  3362 | /***/ })
  3363 | 
View compiled
__webpack_require__
/Users/xxxxxxxx/dev/react-lex-plus/build/index.js:21
  18 | /******/         };
  19 | /******/
  20 | /******/         // Execute the module function
> 21 | /******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  22 | /******/
  23 | /******/         // Flag the module as loaded
  24 | /******/         module.l = true;

标签: javascriptreactjswebpackexternal

解决方案


我遇到这个问题的原因是因为在 webpack.config.js 中,我已将环境设置为“开发”。

当与 externals 语句(见下文)结合使用父项目而不是尝试指向 react-lex-plus 中的 React 实例时,它试图使用 require 函数在浏览器中导入 React。

浏览器没有 require 功能。它是在 NodeJS 中实现的,这就是我收到该错误的原因。

解决方案是将 webpack 配置中的“环境”属性更改回“生产”,代码将使用 NodeJS 编译。

作为补充说明,我仍然需要在 react-lex-plus 目录中npm link ../my-project/node_modules/react运行之前使用npm run build,以使构建成功,因为 react-lex-plus 使用 React 库。

外部声明

externals: {
    react: "commonjs react"
}

推荐阅读