Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

npm - How to avoid React loading twice with Webpack when developing

Given the following directory structure:

my-project
|
|-- node_modules
    |
    |-- react
    |-- module-x
        |
        |--node_modules
            |
            |--react

You can see both my-project and module-x require React. I have the same problem as described on this question, but the suggestion is to remove react from the package.json dependencies. I do that and it works fine, as long as no node_modules are installed in module-x, because Webpack will use React from my-project. But if I'm in the process of developing module-x and the node_modules are installed, Webpack uses React from both my-project and module-x.

Is there a way I could have Webpack make sure only one instance of React is used, even though it's required on two separate levels?

I know I could keep module-x in a separate directory when developing, but it seems like I'd have to publish it and then install it in my-project to test it, and that's not very efficient. I thought about npm link, but had no luck with it since it still has node_modules installed in module-x.

This here sounds a lot like the same challenge I'm having, but it doesn't seem like npm dedupe or Webpack's dedupe option would work. I'm probably not understanding some important detail.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This issue usually arises when using npm link. A linked module will resolve its dependencies in its own module tree, which is different from the one of the module that required it. As such, the npm link command installs peerDependencies as well as dependencies.

You can use resolve.alias to force require('react') to resolve to your local version of React.

resolve: {
  alias: {
    react: path.resolve('./node_modules/react'),
  },
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...