簡體   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