开发时如何避免使用 Webpack 进行两次 React 加载 [英] How to avoid React loading twice with Webpack when developing
问题描述
给定以下目录结构:
my-project
|
|-- node_modules
|
|-- react
|-- module-x
|
|--node_modules
|
|--react
您可以看到 my-project 和 module-x 都需要 React.我遇到了与 这个问题 中所述相同的问题,但建议从 package.json 依赖项中删除 react.我这样做了,只要 module-x 中没有安装 node_modules,它就可以正常工作,因为 Webpack 将使用 my-project 中的 React.但是,如果我正在开发 module-x 并且安装了 node_modules,Webpack 将使用 my-project 和 module-x中的 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.
有没有一种方法可以让 Webpack 确保只使用一个 React 实例,即使它在两个不同的级别上都是必需的?
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?
我知道我可以在开发时将 module-x 保存在一个单独的目录中,但似乎我必须发布它然后将它安装到 my-project> 测试一下,效率不高.我想过 npm link
,但没有成功,因为它仍然在 module-x 中安装了 node_modules.
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.
这里听起来很像我遇到的同样挑战,但它npm dedupe
或 Webpack 的重复数据删除选项似乎不起作用.我可能没有理解一些重要的细节.
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.
推荐答案
这个问题通常在使用 npm link
时出现.链接模块将在其自己的模块树中解析其依赖关系,这与需要它的模块不同.因此,npm link
命令安装 peerDependencies
以及 dependencies
.
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
.
您可以使用 resolve.alias
强制 require('react')
解析为您本地的 React 版本.
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'),
},
},
这篇关于开发时如何避免使用 Webpack 进行两次 React 加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!