vuecli3 webpack dllplugin配置

配置webpack dllplugin提升打包速度,依赖库越大速度越明显

1.全局安装webpack、webpack-cli

npm install webpack -g
npm install webpack-cli -g

查看安装是否成功

webpack -v

 2.package.json

"scripts": {
    "build:dll": "webpack --config webpack.dll.js"
  },

3.webpack.dll.js

entry里是打包要生成的

可以所有的写到一起

 vendors: [
 'lodash',
 'vue',
 'vuex',
 'vue-router',
 'element-ui',
 'echarts',
 'moment',
 'vue-baidu-map',
 'vuescroll',
 'axios',
 'await-to-js',
 'core-js'
]

也可分开打包生成单独的文件 

const path = require('path')
const webpack = require('webpack')
module.exports = {
  entry: {
    lodash: ['lodash'],
    vue: ['vue']
  },
  output: {
    filename: '[name].dll.js',
    path: path.resolve(__dirname, './dll'),
    library: '[name]' // 把文件里的内容通过全局变量暴露出来,变量的名字叫vendors
  },
  plugins: [
    new webpack.DllPlugin({
      name: '[name]', // 对library这个库进行dllplugin的分析
      path: path.resolve(__dirname, './dll/[name].manifest.json')
    })
  ]
}

4.安装add-asset-html-webpack-plugin

npm install add-asset-html-webpack-plugin --save

 5.vue.config.js添加

多文件读取添加

const fs = require('fs')
 chainWebpack(config) {
    const files = fs.readdirSync(path.resolve(__dirname, './dll'))
    files.forEach((file, index) => {
      if (/.*\.dll.js/.test(file)) {
        config.plugin('AddAssetHtmlWebpackPlugin' + index).use(require('add-asset-html-webpack-plugin'), [{
          filepath: path.resolve(__dirname, 'dll', file)
        }])
      }
      if (/.*\.manifest.json/.test(file)) {
        config.plugin('DllReferencePlugin' + index).use(require('webpack/lib/DllReferencePlugin'), [{
          context: __dirname,
          manifest: path.resolve(__dirname, 'dll', file)
        }])
      }
    })
}

单文件添加

 config.plugin('AddAssetHtmlWebpackPlugin').use(require('add-asset-html-webpack-plugin'), [{
      filepath: path.resolve(__dirname, './dll/vendors.dll.js')
    }])
    config.plugin('DllReferencePlugin').use(require('webpack/lib/DllReferencePlugin'), [{
      context: __dirname,
      manifest: path.resolve(__dirname, './dll/vendors.manifest.json')
    }])

 

优化效果:依赖库2M,优化2S秒多

  不使用dllplugin 单文件引入 多文件引入
速度 13060ms、 12905ms、12639ms、12820ms、 13323ms = 平均12949ms 10571ms、10825ms、10159ms、9811ms、9396ms = 平均10152.4ms 12600ms、10823ms、9899ms、 10436ms 、10776ms =10906.8ms
打包分析app.js 5.33M 2.72M 2.72M
请求app.js 16.5M  9.1M  9.1M
vendors.js   2.1M 11.2+26.3+69+131+263+107+70.9+743+779+91.1+15.6+1.4=2308.5KB=2.254M

但是多文件打包又涉及到了另一优化点:应将http请求进行合并,自己进行选择优化

你可能感兴趣的:(webpack,项目常用)