![](/img/trans.png)
[英]How to avoid `loaded two copies of React` error when developing an external component?
[英]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 依赖项中删除反应。 我这样做并且它工作正常,只要没有在module-x中安装 node_modules,因为 Webpack 将使用来自my-project 的React。 但是,如果我正在开发module-x并且安装了 node_modules,则 Webpack 使用来自my-project和module-x的 React。
有没有办法让 Webpack 确保只使用一个 React 实例,即使它在两个不同的级别上是必需的?
我知道我可以在开发时将module-x放在一个单独的目录中,但似乎我必须发布它然后将它安装在我的项目中进行测试,这不是很有效。 我考虑过npm link
,但运气不好,因为它仍然在module-x中安装了 node_modules 。
这听起来很像我遇到的同样的挑战,但它似乎不像npm dedupe
或 Webpack 的重复数据删除选项会起作用。 我可能不理解一些重要的细节。
使用npm link
时通常会出现此问题。 链接模块将在其自己的模块树中解析其依赖关系,这与需要它的模块不同。 因此, npm link
命令会安装peerDependencies
以及dependencies
。
您可以使用resolve.alias
强制require('react')
解析为本地版本的React。
resolve: {
alias: {
react: path.resolve('./node_modules/react'),
},
},
如果您不想(或不能)修改项目配置,那么有一个更简单的解决方案:只需npm link
自身反应回您的项目:
# link the component
cd my-app
npm link ../my-react-component
# link its copy of React back to the app's React
cd ../my-react-component
npm link ../my-app/node_modules/react
以防万一它对其他人有用,上面建议的解决方案对我不起作用,我必须执行以下步骤来解决它:
在图书馆:
peerDependencies
中package.json
,而不是dependencies
或devDependencies
,例如,在我的情况react
:"peerDependencies": {
"react": "^16.8.6",
...
}
npm install
rollup -c
npm 脚本在我的主应用程序中:
package.json
的相对路径将我的库的版本更改为指向我的本地项目,例如"dependencies": {
"my-library": "file:../../libraries/my-library",
...
}
将 resolve.symlinks resolve.symlinks = false
添加到我的主应用程序的 webpack 配置中
将--preserve-symlinks-main
和--preserve-symlinks
到我的package.json
启动脚本中,例如:
"scripts": {
"build": "set WEBPACK_CONFIG_FILE=all&& webpack",
"start": "set WEBPACK_CONFIG_FILE=all&& webpack && node --preserve-symlinks-main --preserve-symlinks dist/server.js",
}
npm install
npm run start
与接受的答案一样,这里是如何使用Craco实现预期结果的方法:
const path = require('path')
module.exports = {
webpack: {
configure: config => {
config = {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
'react': path.resolve('./node_modules/react'),
},
},
}
// console.log(config)
return config
},
},
}
重要的是要注意您不能只将resolve
作为键传递,您必须使用configure
回调进行自己的深度合并。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.