javascript - React 应用无法导入使用 webpack 打包的 react 应用
问题描述
我有一个反应应用程序,我向其中导入了另一个名为react-lex-plus 的反应项目。我管理这两个项目。
当我构建 react-lex-plus 时,webpack 能够捆绑我的应用程序。但是,当我将它导入我的主应用程序时,它会抛出一个错误,说“require is undefined”。
有谁知道为什么会发生这种情况?为什么没有定义require?
我做了以下事情:
确保 react-lex-plus 的 webpack.config.js 具有“externals”属性,其值为“commonjs react”
从 react-lex-plus 中删除 react 并将其链接到我的主项目中的 react 库。
从主项目中取消 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;
解决方案
我遇到这个问题的原因是因为在 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"
}
推荐阅读
- database - 在考虑时间维度时,基数如何在 ER 图中起作用?
- android - 在 DataSource.Invalidate() 之后新的 PagedList 只有一页
- python - PyTorch 获取模型的所有层
- python - django.db.utils.OperationalError:没有这样的表:
- php - PHP - PDO 运行多个选择查询
- html - 使用网格时如何在网站底部放置页脚?
- python - 为什么共享的价值没有改变?
- python - 无法使用 pandas 读取修改后的 csv 文件
- javascript - 如何同步执行 socket.io 端点
- c - 附加返回指针/转换错误的字符串的函数