vue客户端渲染首屏优化之道

 

提取第三方库,缓存,减少打包体积

1、 dll动态链接库, 使用DllPlugin DllReferencePlugin,将第三方库提取出来另外打包出来,然后动态引入html。可以提高打包速度和缓存第三方库
这种方式打包可以见京东团队的gaea方案
https://www.npmjs.com/package/gaea-cli
2、webpack4的splitChunks或者 webpack3 CommonsChunkPlugin 配合 externals (资源外置)
主要是分离 第三方库,自定义模块(引入超过3次的自定义模块被分离),webpack运行代码(runtime,minifest)。
配合externals,意思将第三方库外置,用cdn的形式引入,可以减少打包体积。
详细代码
在webpack.config.js(peoduction环境下)

externals: {     'vue': 'Vue', //vue 是包名 Vue是引入的全局变量     'vue-router': 'VueRouter',     'vuex': 'Vuex',     'axios': 'axios',     'iview': 'iview' //iview },

然后再main.js或者任何地方不再引入 比如vue,直接使用上面提供的变量

上面没有import vue进来,项目中照常使用Vue这个全局变量。
既然没有import vue 自然不会打包vue,然后你会发现你的vendor.js会从700kb+ 减少到 30-40kb,非常棒的优化。

webpack4 splitChunk的配置

//提取node_modules里面的三方模块 module.exports = {     optimization: {         splitChunks: {             cacheGroups: {                 vendor: {                     chunks: "initial",                     test: path.resolve(__dirname, "node_modules") // 路径在 node_modules 目录下的都作为公共部分           name: "vendor", // 使用 vendor 入口作为公共部分                     enforce: true,                 },             },         },     }, } //提取 manifest (webpack运行代码) {     runtimeChunk: true; }

webpack3 CommonsChunkPlugin 的配置,写在plugins中

 // split vendor js into its own file     new webpack.optimize.CommonsChunkPlugin({       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         )       }     }),     // extract webpack runtime and module manifest to its own file in order to     // prevent vendor hash from being updated whenever app bundle is updated     new webpack.optimize.CommonsChunkPlugin({       name: 'manifest',       minChunks: Infinity     }),     // This instance extracts shared chunks from code splitted chunks and bundles them     // in a separate chunk, similar to the vendor chunk     // see: upload/201904171721504116.png" style="margin: 0px; padding: 0px; border: 0px; max-width: 900px; height: auto;" alt="" />
我们可以直接看到786kb的大文件是来自于 test1.vue和test2.vue的vendor包(第三方库),然后进入test1.vue,echarts就是问题源,关于解决就是把echarts等第三方库外置。详细见上面资源外置。

第二种:
原理:根据每个chunk里面的module id 去唯一化这个chunk的name,只要里面的module没有增多或减小,那么它的名字是不会变的

new webpack.NamedChunksPlugin(chunk => {   if (chunk.name) {     return chunk.name;   }   return 
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信


和一个专注代码17年的团队,一起学习,踏实的成长,朴素、真挚的面对世界

万码学堂课程咨询电话0532-85025005

鲁ICP备09077726号-5