我已经创建了模块A,这是我的React应用程序的组件库。我计划在模块B上使用,这是我实际的React应用程序。
我有一个index.js,我从模块A导出组件,使用可加载的组件,以以下方式
import loadable from '@loadable/component'
export const Theme = loadable(() => import('./Theme'))
export const OtherComponent = loadable(() => import('./OtherComponent'))
export const OtherComponent2 = loadable(() => import('./OtherComponent2'))
因此,我使用以下webpack配置构建并部署模块A到npm
const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const TerserPlugin = require("terser-webpack-plugin")
const LoadablePlugin = require('@loadable/webpack-plugin')
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
minimize: true,
concatenateModules: false,
minimizer: [new TerserPlugin({
terserOptions: {
keep_fnames: true
}
})],
},
entry: {
main: './src/components/index.js',
},
output: {
publicPath: '/',
filename: "[name].js",
path: path.resolve(__dirname, "dist"),
library: "myComponentLibrary",
libraryTarget: "umd",
globalObject: "this"
},
externals: {
react: {
root: 'React',
commonjs: 'react',
commonjs2: 'react',
amd: 'react',
},
},
plugins: [new CleanWebpackPlugin(), new LoadablePlugin()],
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
cacheDirectory: true
}
}
],
},
{
test: /.(jpe?g|png|gif|svg)$/,
type: 'asset/inline'
},
]
}
}
我期望当我在模块B上安装模块A时能够导入和渲染我的组件,但我得到以下错误:
loadable-components: failed to asynchronous load component {fileName: undefined, chunkName: undefined, error: 'Loading chunk 2661 failed. 'n(error: 2661.js)'}
请指导我如何解决这个问题
如果在开发中一切都运行良好,但在生产中却不是,并且您面临此错误,请将此<base href="/"/>
添加到index.html的头部:
<!DOCTYPE html>
<html>
<head>
<base href="/"/>
<meta charset="utf-8" />
<title>Foo project</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
现在,我认为一切都很顺利。这个问题是由于html5的路由,你可以搜索它。