javascriptreactjswebpackwebpack-externals

Using webpack externals causes 'require is not defined' error in browser


I'm trying to develop a custom react component and I want to publish it on npm later. I've got the following webpack config:

var path = require('path');

module.exports = (env, args) => {
  entry: './src/index.js',
    output: {
    path: path.resolve(__dirname, 'build'),
      filename: 'index.js',
        libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|build)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"]
          }
        }
      }
    ]
  }
  externals: {
    react: 'commonjs react'
  }
}

When running in the browser, I get 'require is not defined'. Why does webpack bundle a require statement? If I remove externals from the config, everything runs alright.

EDIT: By running in the browser, I mean that I've created a client project for the lib using npx create-react-app. There, I've imported my bundle via an import statement.


Solution

  • I got it to work by exposing the library as Universal Module:

    libraryTarget: 'umd'
    

    And specifying externals like this:

    externals: [{
      'react': {
        root: 'React',
        commonjs2: 'react',
        commonjs: 'react',
        amd: 'react'
      }
    }, {
      'react-dom': {
        root: 'ReactDOM',
        commonjs2: 'react-dom',
        commonjs: 'react-dom',
        amd: 'react-dom'
      }
    }],