I was creating an npm package in React, using create-react-app. Since react
and react-dom
are assumed to be in the host project, I listed them as peerDependencies and devDependencies in my package.json.
I learned that this way the two still get bundled, and to prevent that I have to list them in the externals of the webpack config, which I did succesfully:
externals: {
react: {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React',
},
'react-dom': {
commonjs: 'react-dom',
commonjs2: 'react-dom',
amd: 'ReactDOM',
root: 'ReactDOM',
},
},
My question is: why do I have to go through this second step? Shouldn't listing them as peerDependencies be sufficient? And if not, how do peerDependencies differ from the regular dependencies in that case?
The Webpack Externals are used to ignore the packages from the application while bundling and adding them as external CDN script references.
Webpack node modules externals. 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.
Peer Dependencies: In package. json file, there is an object called as peerDependencies and it consists of all the packages that are exactly required in the project or to the person who is downloading and the version numbers should also be the same. That is the reason they were named as peerDependencies.
TL;DR: dependencies and devDependencies are used to make a difference between the libraries that will be (or won't be) in your final bundle. peerDependencies are useful only if you want to create and publish your own library.
Peer dependencies are understood by npm, externals are understood by webpack. Both mean the same thing, but are dealt with by entirely different pieces of software.
While running npm install
will not install any peer dependencies, webpack will still try to walk the dependency tree to try and find them if they are referenced in the code. Marking them as external tells webpack to explicitly ignore them and not attempt to walk that dependency branch, even if those peer dependencies have been installed.
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