公共脚本分离
思路:将react、react-dom基础包通过cdn引入,不打入bundle中
方法一:SplitChunksPlugin(webpack4内置插件)官网地址
chunks参数说明
.async 异步引入的库进行分离(默认)
.initial 同步引入的库进行分离
.all 所有引入的库进行分离(推荐)
//三方库分离
optimization:{
splitChunks: {
cacheGroups: {
commons: {
test: /(react|react-dom)/,
name: "vendors",
chunks: "all"
}
}
}
}
//公共脚本分离
optimization:{
splitChunks: {
minSize:0,
cacheGroups: {
commons:{
name:'commons',
chunks:"all",
minChunks:2 //至少引用2次,才打包出commons文件
}
}
}
}
引入方法
new HTMLWebpackPlugin({
chunks:["vendors",pageName]
})
打包结果
image.png
方法二:html-webpack-externals-plugin
cnpm i html-webpack-externals-plugin -D
webpack.prod.js
new HtmlWebpackExternalsPlugin({
externals: [
{
module: 'react',
entry: 'https://unpkg.com/react@16/umd/react.production.min.js',
global: 'React',
},
{
module: 'react-dom',
entry: 'https://unpkg.com/react-dom@16/umd/react-dom.production.min.js',
global: 'ReactDOM',
},
],
})
index.html
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
</body>
网友评论