React App无法导入与Webpack打包在一起的React App

问题描述

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

当我构建react-lex-plus时,webpack可以捆绑我的应用程序。但是,当我将其导入到主应用程序中时,它将引发错误提示“ require is undefined”。

有人知道为什么会这样吗?为什么要求没有定义?

我已完成以下操作:

  1. 确保react-lex-plus'webpack.config.js具有“外部”属性,其值表示为“ commonjs react”

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

  3. 从主项目取消链接React,并将react安装在react-lex-plus中。

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

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;

解决方法

我遇到该问题的原因是因为在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"
}