gpt4 book ai didi

Webpack 5 vendor block 命名

转载 作者:行者123 更新时间:2023-12-04 07:50:58 25 4
gpt4 key购买 nike

在 webpack 4 中,vendor chunks 的名称如 vendors~main~secondary.js ,它们指的是与它们相关的块。现在,在 webpack 5 中, vendor 块名称是这样的:vendors-node_modules_react-dom_index_js.js ,这确实不太容易阅读和理解。
关于在使用 webpack 5 时如何回到 webpack 4 行为的任何提示?
我想我得对 splitChunks.name 做些事情,但我找不到合适的函数来做到这一点。
编辑
虽然@MrP01 的回答更彻底,并且更深入地了解如何使用 splitChunks.name ,这是我最终使用的一个简短片段,它使我能够回到确切的旧行为。

optimization: {
splitChunks: {
chunks: 'all',
name: (module, chunks, cacheGroupKey) => {
const allChunksNames = chunks.map((chunk) => chunk.name).join('~');
const prefix = cacheGroupKey === 'defaultVendors' ? 'vendors' : cacheGroupKey;
return `${prefix}~${allChunksNames}`;
},
},
},

最佳答案

我对 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 设置,没有特定的缓存组,适用于所有缓存组。
我还启用了块、 Assets 名称和提取的 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"
}),
],
};
};
这导致文件名超出名称限制,结果输出文件夹中的文件名更短更简洁。

关于Webpack 5 vendor block 命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66986664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com