2

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.

4
  • Which output are you trying to use? commonjs means that a require() will be available because that is part of the CommonJS spec.
    – zero298
    Sep 23, 2019 at 18:45
  • Can yoe elaborate how you run it in the browser exactly?
    – emrhzc
    Sep 23, 2019 at 18:45
  • @EmrahIzci I've updated the question. Sep 23, 2019 at 19:08
  • @zero298 I want it to be importable by others using npm. So, I guess you are right, that's the cause. But shouldn't my client project transform the require statement then? Sep 23, 2019 at 19:12

1 Answer 1

1

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'
  }
}],

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.