24

I am building a React library and using Webpack to bundle it. I'm well aware of the concept behind dependencies and peer dependencies.

In the project, React is specified as a peer dependency.

"peerDependencies": {
  "react": ">= 16.3.0",
  "react-dom": ">= 16.3.0"
}

This is my build script

"build": "webpack --config webpack.config.babel.js"

and this is my webpack.config.babel.js

import path from 'path';
import CleanWebpackPlugin from 'clean-webpack-plugin';
const packageJson = require('./package.json');

export default () => ({
  mode: 'production',
  entry: {
    index: path.join(__dirname, 'src/index.js')
  },

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    library: packageJson.name,
    libraryTarget: 'umd'
  },

  module: {
    rules: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        include: path.join(__dirname, 'src'),
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env', '@babel/preset-react']
            }
          }
        ]
      },
      {
        test: /\.(scss)$/,
        loader: 'style-loader!css-loader!sass-loader'
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.jsx', '.scss']
  },

  plugins: [new CleanWebpackPlugin(['dist/*.*'])],
  optimization: {
    splitChunks: {
      name: 'vendor',
      minChunks: 2
    }
  }
});

Every time I build, React code is included in the bundled file. I'm unsure about how to bundle the library without including React in the bundled file.

Dinesh Pandiyan
  • 5,814
  • 2
  • 30
  • 49
  • Do you use `mode: 'production'` in your Webpack config both for an unminified and minified build because this way Webpack always applies tree-shaking? – tonix Mar 21 '20 at 20:25
  • Libraries don't need to be bundled. Their consumers will bundle them anyway. If you forego bundling your library, you'll automatically solve the `peerDependencies` problem. – Steve Aug 02 '22 at 14:39

1 Answers1

38

I figured it out.

Webpack has a configuration called externals. Anything specified as an external will not be bundled together.

All I had to do was to add this config to webpack.config.babel.js

externals: {
  react: 'react',
  reactDOM: 'react-dom'
}

More info here - webpack externals

Dinesh Pandiyan
  • 5,814
  • 2
  • 30
  • 49