路由使用按需加载(懒加载)
{
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: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 tomain
(if you don't use theentry: {}
), I set mine tomain
in my example. This tells webpack which entry chunk (that contains in its dependency graph) theimport()
or asyncrequire.ensure
statements are found and to include those chunks as part of the grouping algorithm.