webpack3 打包分析插件 和 分包技术(压缩打包体积)

530 阅读2分钟

webpack3 打包分析插件(webpack-bundle-analyzer) 和 分包技术(代码分离,压缩打包体积)

一、打包分析插件

  • 插件安装

    npm install --save-dev webpack-bundle-analyzer

  • 在webpack的生产配置中(webpack.prod.conf.js)引入

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
....
module.exports ={
  ...
  plugins: [
    new BundleAnalyzerPlugin()  // 使用默认配置
    // 默认配置的具体配置项
    // new BundleAnalyzerPlugin({
    //   analyzerMode: 'server',
    //   analyzerHost: '127.0.0.1',
    //   analyzerPort: '8888',
    //   reportFilename: 'report.html',
    //   defaultSizes: 'parsed',
    //   openAnalyzer: true,
    //   generateStatsFile: false,
    //   statsFilename: 'stats.json',
    //   statsOptions: null,
    //   excludeAssets: null,
    //   logLevel: info
    // })
  ],
  ...
}

打包时对代块进行拆分,避免都打包到vendor中

1. 删除多余的第三方库

检查自己package.json文件下dependencies里面有哪些是安装引用了但是没用的。因为里面可能存在当时做项目测demo引入的库忘记删除,挨个挨个筛选,找到以后执行下面的命令将其卸载。

    ` npm un xxxx  `

2. 配置webpack将剩下的vendor拆分成体积较小的多个文件

    // webpack.base.conf.js
    // 修改entry入口,将package.json中dependencies下的依赖拆分到不同的vendor中
    // 这里可以反复进行,直到打包出来的每个vendor不太大,也不太小
    entry: {
        vendor1: ["axios", "vuex", "vue", "vue-router"],
        vendor2: ["echarts"],
        vendor3: ["echarts-extension-amap", "echarts-liquidfill", "three-css2drender","three-obj-mtl-loader","three-orbit-controls"],
        vendor4: ["echarts-gl"],
        vendor5: ["element-ui"],
        vendor6: ["node-sass"],
        vendor7: ["three"],
        vendor8: ["vue-amap","vue-seamless-scroll"],
        vendor9: ["xlsx"],
        app: './src/main.js'
    },
    // webpack.base.conf.js
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            // 这里要跟entry配置的顺序反着来,否则不能成功
            names: ["vendor9","vendor8", "vendor7", "vendor6","vendor5", "vendor4", "vendor3","vendor2", "vendor1"],
            minChunks: Infinity

            // 下面是cli默认配置
            // name: 'vendor',
            // minChunks (module) {
            //   // any required modules inside node_modules are extracted to vendor
            //   return (
            //     module.resource &&
            //     /\.js$/.test(module.resource) &&
            //     module.resource.indexOf(
            //       path.join(__dirname, '../node_modules')
            //     ) === 0
            //   )
            // }
        }),
    ]

再执行 npm run build 打包生成一堆vendorX.XXX.js,体积都比较小了

image.png

image.png

可以看到最大的包是1.05MB,这个已经是单独的包了,要继续压缩就得用gzip压缩技术了

GZIP压缩技术。。。。待续。。。。