vuecli3项目中webpack4配置(二)提高打包速度

2,133 阅读1分钟

将静态资源文件(运行依赖包)与源文件分开打包,先使用DllPlugin给静态资源打包,再使用DllReferencePlugin让源文件引用资源文件。package.json中新加一条命令:

"dll": "webpack --config webpack.dll.config.js"

新建webpack.dll.config.js

const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const webpack = require('webpack')

module.exports = {
  mode: 'production',
  entry: {
    vendor: ['vue/dist/vue.runtime.esm.js', 'vuex', 'vue-router', 'element-ui', 'axios']
  },
  output: {
    filename: '[name].dll.js',
    path: path.resolve(__dirname, 'dll'),// 打包后文件输出的位置
    library: 'dll_[name]'
  },
  plugins: [
    new CleanWebpackPlugin(), 
    new webpack.DllPlugin({
      name: 'dll_[name]',//和output. library保持一致
      path: path.join(__dirname, 'dll', '[name].manifest.json'),
      context: __dirname
    })
  ]
}

执行npm run dll生成dll文件夹,即生成了动态链接库。

修改vue.config.js添加DllReferencePlugin的配置

vue.config.js
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const dllReference = (config) => {
  config.plugin('vendorDll')
    .use(webpack.DllReferencePlugin, [{
      context: __dirname,
      manifest: require('./dll/vendor.manifest.json')
    }])
  config.plugin('addAssetHtml')
    .use(AddAssetHtmlPlugin, [
      [
        {
          filepath: require.resolve(path.resolve(__dirname, 'dll/vendor.dll.js')),
          outputPath: 'dll',
          publicPath: '/dll'
        }
      ]
    ])
    .after('html')
};

 chainWebpack: config => {
    if(process.env.NODE_ENV === 'production'){
      dllReference(config)
    }
  }

AddAssetHtmlPlugin插件的作用是添加js或者css资源到由html-webpack-plugin插件自动生成的文件中。

再执行npm run build可以看到打包时间明显缩短。

参考资料

vuecli3+webpack4优化实践(删除console.log和配置dllPlugin)