webpack打包体积优化

 

优化:

1:外部引入模块(cdn)
     如 jquery,zepto,d3, bootstrap这些固定的lib 使用cdn直接引用就可以,没有必要打包到build,有效利用302。

2:图标优化
     不管后台还是移动端避免不了icon的使用,使用字体图标,还需引入字体文件,如果字体丢失 会影响到icon显示效果,推荐转换base64 后引用。

 

3:统一模块

    如:moment我们可能在多个页面使用  没必要每个页面进行import引入,可以在入口文件(index.js 或main.js)全局配置

   例如:

 

      import Vue from 'vue'           
      Vue.prototype.$moment = moment;

 

    以后在每个页面都可以直接使用 this.$moment ,  不在需要每个页面import 'moment' 。

     moment 有各种语言包,总大小200k+,如使用webpack打包 建议过滤掉其他语言

    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) 
    或 new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /zh-cn/)

4:分离第三方库


 entry: {    
  app: './src/main.js', //设置入口文件
  
  vendors: ['vue', 'vue-router', 'moment']
},



    
  
plugins[
        new webpack.optimize.CommonsChunkPlugin({
          name: ['vendor', 'manifest'], // 如果有manifest 每次打包压缩后的文件不会改变hash
            minChunks: function (module, count) {
                // 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
                )
            }
        }),]  

 

  使用 CommonsChunkPlugin插件配置 每次build后,都会重新设置hash,导致Etag不同,每次上线都会更新Etag, 无法利用浏览器缓存。

 下图优化大小:

 后台项目:总大小 20M 减少到4.2M   后台4.2M, 在开启gzip压缩下,勉强凑合。

  

优化后:
 



移动端:2.0M减少到830K,开启gzip 大概在400-500k左右。

 

 

 



 

      

 

 

  

posted @ 2017-08-22 16:03  peerless_she  阅读(3708)  评论(0编辑  收藏  举报