打包部署
Webpack 应用分割与生产环境部署
SplitChunks
代码分割是提升

不同于
- 新的块是在多个模块间共享,或者来自于
node_modules 目录; - 新的块在压缩之前的大小应该超过
30KB ; - 页面所需并发加载的块数量应该小于或者等于
5 ; - 初始页面加载的块数量应该小于或者等于
3 ;
splitChunks: {
chunks: "async",
minSize: 30000,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
值得一提的是,这里的initial
async
all
三个配置,上述配置即是分别针对初始initial
,那么它将忽略通过动态导入的模块包包含的第三方库代码。而
{
splitChunks: {
// 禁止默认 splitChunks 行为,防止生成 a~b.js 这样的公用包
default: false,
cacheGroups: {
commons: {
chunks: "initial",
minChunks: 2,
maxInitialRequests: 5, // The default limit is too small to showcase the effect
minSize: 0 // This is example is too small to create commons chunks
},
vendor: {
test: /node_modules/,
chunks: "initial",
name: "vendor",
priority: 10,
enforce: true
}
}
}
}
我们也可以设置
{
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(
/[\\/]node_modules[\\/](.*?)([\\/]|$)/,
)[1];
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`;
},
}
runtimeChunk

// Webpack 3 之后支持显式指定 Chunk 名
import(/* webpackChunkName: "optional-name" */ "./module")
.then((module) => {
/* ... */
})
.catch((error) => {
/* ... */
});
webpackJsonp([0], {
KMic: function(a, b, c) {
...
},
co9Y: function(a, b, c) {
...
},
});
如果是使用
构建目标
UMD
(function (define) {
define(function () {
// ...
});
})(
typeof module === "object" && module.exports && typeof define !== "function"
? function (factory) {
module.exports = factory();
}
: define
);
如果在代码里使用了 export default xxx
这种形式作为导出,那么最终输出的模块中会出现 libraryName.default
这种形式。如果希望以