【Vue】webpack如何避免懒加载里的重复打包第三方库
路由使用按需加载(懒加载)
{path: 'a',
component: resolve => require(['a.vue'], resolve)
},
{
path: 'b',
component: resolve => require(['b.vue'], resolve)
},
a.vue/b.vue
import echarts from 'echarts';//同时需要echarts图表库 所以都import了echarts
由于路由使用了懒加载
这就导致了a.vue与b.vue将被单独打包为两个js文件以实现按需加载
而这两个js内都引用了echarts,所以这两个js中都包含了完整的echarts,所以文件都很大。
如何解决这个问题,求教。
回答
It sounds like you would like to create a shared async chunk. To do this you will need to use the CommonsChunkPlugin
.
CommonsChunkPlugin()
can allow you to manually specify conditions that if satisfied, will move modules shared between multiple chunks (async/sync) into their own bundle of the same type.
So in this case we would like to say:
"Hey webpack, if there is a module which is used between at least 2 lazy chunks, let's separate that module into a shared chunk to improve caching"
To express this using CommonsChunkPlugin
you would use the following properties:
const webpack = require("webpack");module.exports = {
plugins: [
new webpack.CommonsChunkPlugin({
name: "main", // <== should be entry key which contains the lazy imports
async: true,
minChunks: 2
})
]
}
Here is a before and after photos of the described case above working in webpack 3.1+:
Before
After
Important
For creation of a shared async commons chunk to work, you must specify the name
property to equal the entry keys you are using. Since webpack defaults the entry key to main
(if you don't use the entry: {}
), I set mine to main
in my example. This tells webpack which entry chunk (that contains in its dependency graph) the import()
or async require.ensure
statements are found and to include those chunks as part of the grouping algorithm.
@player0 求教,解决了吗,我还是没有提取成功,不知道是不是配置错了,我只配置了这一个地方,有其他地方需要配置吗
new webpack.optimize.CommonsChunkPlugin({ name: "lazy",
async: true,
minChunks: 2
})
以上是 【Vue】webpack如何避免懒加载里的重复打包第三方库 的全部内容, 来源链接: utcz.com/a/77600.html