vuecli3項目中webpack4配置(二)提升打包速度

將靜態資源文件(運行依賴包)與源文件分開打包,先使用DllPlugin給靜態資源打包,再使用DllReferencePlugin讓源文件引用資源文件。package.json中新加一條命令:css

"dll": "webpack --config webpack.dll.config.js"
複製代碼

新建webpack.dll.config.jshtml

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

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

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插件自動生成的文件中。ios

再執行npm run build能夠看到打包時間明顯縮短。web

參考資料vue-router

vuecli3+webpack4優化實踐(刪除console.log和配置dllPlugin)vuex

相關文章
相關標籤/搜索