React - defined externals modules in webpack config produce“Module not found:导入库时无法解析“

soat7uwm  于 2023-08-06  发布在  Webpack
关注(0)|答案(1)|浏览(133)

在Webpack配置中的React库my-library中,我定义了以下内容:

...
module.exports = {
    output: {
        path: __dirname,
        filename: "dist/index.js",
        libraryTarget: "umd",
    },
    ...
    externals: {
        'react': 'react_and_react_dom.React',
        'react-dom': 'react_and_react_dom.ReactDOM',
    },
}
...

字符串
然而,当我在另一个React项目中导入这个库时,我得到:

Failed to compile.

./node_modules/my-library/dist/index.js
Module not found: Can't resolve 'react_and_react_dom.React' in '{path_to_main_app}\node_modules\my-library\dist'


在主应用程序上-我们在页面上加载React和ReactDOM-因此当我在浏览器中检查时-我定义了这些:

console.log(window.react_and_react_dom)
> Object { React: {…}, ReactDOM: {…} }


你知道我错过了什么吗

ncgqoxb0

ncgqoxb01#

像这样指定externals

externals: {
    "react": {
        "commonjs": "react",
        "commonjs2": "react",
        "amd": "react",
        "root": "React"
    },
    "react-dom": {
        "commonjs": "react-dom",
        "commonjs2": "react-dom",
        "amd": "react-dom",
        "root": "ReactDOM"
    }
},

字符串
解决了我的问题。

相关问题