问题描述
在 webpack 4 中,vendor 块的名称如 vendors~main~secondary.js
,它们指的是与它们相关的块。现在,在 webpack 5 中,供应商块的名称是这样的:vendors-node_modules_react-dom_index_js.js
,这确实不太可读和易懂。
关于如何在使用 webpack 5 时返回到 webpack 4 的行为的任何提示?
我想我必须对 splitChunks.name
做些事情,但我找不到合适的函数来做到这一点。
解决方法
我对 webpack 5 中的新命名方案的感觉非常相似。经过相当多的努力和测试,我想出了以下方法,将函数句柄传递给 filename
属性。
为了获得“更漂亮”的名字——这当然取决于每个人的个人判断——以下函数规范化了名字并去除了它们的大部分和不必要的部分。
function normalizeName(name) {
return name.replace(/node_modules/g,"nodemodules").replace(/[\-_.|]+/g," ")
.replace(/\b(vendors|nodemodules|js|modules|es)\b/g,"")
.trim().replace(/ +/g,"-");
}
主要问题是被拆分的块的命名。当前的文档对此不是很明确,但是 config.optimization.splitChunks
中配置的 cacheGroup 设置(没有特定的 cacheGroup)适用于所有 cacheGroup。
我还启用了块、资产名称和提取的 css 的规范化。
module.exports = async () => {
return {
config: {
context: BASE,entry: entrypoints,output: {
path: path.resolve(`./.dev/bundles/${locale}`),publicPath: `/static/bundles/${locale}/`,filename: (pathData) => {
return normalizeName(pathData.chunk.name) + ".js";
},chunkFilename: (pathData) => {
return normalizeName(pathData.chunk.id) + ".js";
},},devtool: false,optimization: {
splitChunks: {
chunks: "all",name(module,chunks,cacheGroupKey) {
const moduleFileName = module.identifier().split("/").reduceRight((item) => item);
// const allChunksNames = chunks.map((item) => item.name).join("-");
return normalizeName(moduleFileName.replace(/[\/]/g,"-"));
}
}
},module: {
rules: [
{
test: /\.css$/,use: [
MiniCssExtractPlugin.loader,cssLoader,postCssLoader
]
},{
test: /\.(ttf|woff|eot|png|jpg|jpeg|svg)$/,type: "javascript/auto",loader: "file-loader",options: {
name: (resourcePath,resourceQuery) => {
let ext = path.extname(resourcePath); // for instance ".jpg"
return normalizeName(path.basename(resourcePath).slice(0,-ext.length)) + ext;
}
}
}]
},plugins: [
new MiniCssExtractPlugin({
filename: (pathData) => normalizeName(pathData.chunk.name) + ".css",chunkFilename: (pathData) => normalizeName(pathData.chunk.id) + ".css"
}),],};
};
这导致文件名超出名称限制,结果输出文件夹中的文件名更短更简洁。