javascript - webpack如何避免懒加载里的重复打包第三方库

查看:655
本文介绍了javascript - 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.

这篇关于javascript - webpack如何避免懒加载里的重复打包第三方库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆