How to make a linked component peerDepdencies use

2020-04-24 16:36发布

问题:

  • I am using npm version 3 (version relevant because of the new way peerDependencies behave in version 3).
  • I have a reactjs app called "game" and a reactjs component called "player".
  • I am using webpack-dev-server to run "game" app.
  • react and react-dom are dependencies of game app and peerDependencies of the player component.

I would like to link player component to game app.

I have done:

cd /player
npm link
cd /game
npm link player

When I run webpack-dev-server program, I get the following error message:

Hash: 09968e7401389f50049f
Version: webpack 1.12.2
Time: 339ms
chunk    {0} app.js, 0.14192ce06d8b6f8abb91.hot-update.js, app.css (app) 2.32 MB
     + 576 hidden modules

ERROR in ../player/index.js
Module not found: Error: Cannot resolve module 'react' in /player
 @ ../player/index.js 21:13-29

How do I make player component to use game ./node_modules for the peerDependences?

回答1:

After a bit of digging, I have found a solution in the webpack documentation: npm linked modules doesn’t find their dependencies.

Simply add resolve.fallback (and resolveLoader.fallback if your dependencies have loader specific logic, such as using CSS Modules) to your webpack config:

resolve: {
    fallback: path.resolve(__dirname, './node_modules')
},
resolveLoader: {
    fallback: path.resolve(__dirname, './node_modules')
}

The fallback setting will make webpack loader look into the local ./node_modules path for any dependencies that cannot be resolved, including the dependencies of the dependencies of the main app itself. As a result, all peerDependencies of the main app dependencies will be resolved against the main app ./node_modules.