我正在研究一个需要一些可选对等依赖项的库。
"peerDependencies": {
"react-dnd": ">=14.0.0",
"react-dnd-html5-backend": ">=14.0.0",
},
"peerDependenciesMeta": {
"react-dnd": {
"optional": true
},
"react-dnd-html5-backend": {
"optional": true
}
},
我认为我可能需要它们的方式是
try {
DndProvider = require('react-dnd').DndProvider;
HTML5Backend = require('react-dnd-html5-backend').HTML5Backend;
} catch (err) {
// optional module not installed
}
我将它们声明为外部对象,如下所示:
externals: {
"react-dnd": {
commonjs2: 'react-dnd',
commonjs: 'react-dnd',
amd: 'react-dnd',
root: 'react-dnd',
},
"react-dnd-html5-backend": {
commonjs2: 'react-dnd-html5-backend',
commonjs: 'react-dnd-html5-backend',
amd: 'react-dnd-html5-backend',
root: 'react-dnd',
},
}
现在,这可行,但如果强制消费者安装依赖项,否则他们将收到一条compiled with warnings
Module not found: Error: Can't resolve 'react-dnd'
消息
我如何告诉 webpack 不在乎模块是否不存在?
我发现一种方法是使用,但在这里__non_webpack_require__
阅读答案后我感到气馁