React配置 webpack多页应用打包失败,报错Cannot read property ‘filter’ of undefined解决方案
react的多页应用,运行 npm run build 后控制台报错:
npm run build
node scripts/build.js
Creating an optimized production build...
Failed to compile.
Cannot read property 'filter' of undefined
- 控制台并没有明确提示错误位置,所以在webpack.config.js 文件中找用到 filter方法的地方检查。以为是 entry
配置有问题,但经过检查发现问题并不在 entry 之后对比了不同版本的 create-react-app 生成的
webpack.config.js文件中所用到 filter方法的地方,发现新的配置文件中 ManifestPlugin
的配置项发生了变化 可以看到配置项中多了 generate 这一属性,其中就有用到 filter方法。其中
entrypoints.main 调用了 filter方法,经过输出得知 entrypoints.main 的值是与 entry
配置对应的。 默认情况下 entry 的值是一个 Array,因此 entrypoints.main 的值也一个
Array,但是配置多页面时是把其改为了 Object,Object 没有 filter方法,因此报错
解决方法:
- 修改 entrypoints.main 中的 main 为你在 entry 中配置的项目首页的 key。我的 entry 配置中首页的
key 为 index ,因此可改为 entrypoints.index
修改之前
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
修改之后
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.index.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),