Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to list my peerDependencies as externals in the webpack config when creating a package?

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?

like image 399
syberen Avatar asked Jul 29 '19 14:07

syberen


People also ask

What is externals in Webpack config?

The Webpack Externals are used to ignore the packages from the application while bundling and adding them as external CDN script references.

What is the use of Webpack node externals?

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.

What is peerDependencies in package JSON?

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.

What's the difference between dependencies devDependencies and peerDependencies in package JSON file?

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.


1 Answers

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.

like image 186
Soviut Avatar answered Sep 25 '22 10:09

Soviut