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.
Webpack builds a dependency graph used internally Now all modules that are used in your app are included in the dependency graph. Your project have many installed dependencies in the node_modules folder that should not be included in your client-side JavaScript production bundle.
Webpack allows you to define externals - modules that should not be bundled. When bundling with Webpack for the backend - you usually don't want to bundle its node_modules dependencies. This library creates an externals function that ignores node_modules when bundling in Webpack.
Webpack externals tell Webpack to exclude a certain import from the bundle. Often externals are used to exclude imports that will be loaded via CDN. For example, suppose you are implementing server-side rendering with Vue and Express, but your client-side code imports Vue via a CDN.
Peer dependencies are almost like normal dependencies, but instead of defining a strong requirement between A and B (i.e the project you're developing and the project it depends on), they're meant to specify a package that your code requires, but doesn't directly require it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With