Search code examples
javascriptreactjswebpackexternal

React app fails to import react app packaged with webpack


I have a react application to which I import another react project called react-lex-plus. I manage both projects.

When I build react-lex-plus, webpack is able to bundle my applicaiton. However, when I import it onto my main application, it would throw an error saying "require is undefined".

Does anyone know why this maybe happening? Why is require not defined?

I've done the following:

  1. Ensure react-lex-plus' webpack.config.js has "externals" property with the value said to "commonjs react"

  2. remove react from react-lex-plus and link it to react library in my main project.

  3. Unlink react from main project and install react in react-lex-plus.

Below is the error message from the browser.

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;

Solution

  • The reason I was having that issue was because in webpack.config.js, I have set the environment to "development".

    When combined with the externals statement (see below) as a means to use the parent project instead of attempting to point to an instance of React within react-lex-plus, it was attempting to import React within the browser using require function.

    Browsers do not have require function. It is implemented in NodeJS, which is why I was getting that error.

    The solution is to change the "environment" property in webpack config back to "production", which the code will be compiled using NodeJS.

    As an added note, it is still necessary for me to use npm link ../my-project/node_modules/react before running npm run build within react-lex-plus directory in order for build to be successful since react-lex-plus uses React library.

    externals statement

    externals: {
        react: "commonjs react"
    }