繁体   English   中英

React 应用无法导入使用 webpack 打包的 React 应用

[英]React app fails to import react app packaged with webpack

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

当我构建 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-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;

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

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

浏览器不需要 function。它是在 NodeJS 中实现的,这就是我收到该错误的原因。

解决方案是将 webpack 配置中的“environment”属性改回“production”,代码将使用 NodeJS 编译。

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

外部声明

externals: {
    react: "commonjs react"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM