web优化 之 DllPlugin

本文Demo的完整工程代码, 参考dll-test

创建工程

vue init webpack-simple dll-test

cd dll-test && cnpm i
npm run build

Time: 3602ms

第三方库

cnpm i --save vuex vue-router axios lodash element-ui
vim src/main.js
import _ from 'lodash'
import vuex from 'vuex'
import ElementUI from 'element-ui'
import axios from 'axios'
import vueRouter from 'vue-router'
npm run build

Time: 12605ms

DllPlugin

  • webpack.dll.config.js
var path = require("path");
var webpack = require("webpack");

module.exports = {
    // 你想要打包的模块的数组
    entry: {
        vendor: ['vue', 'lodash', 'vuex', 'axios', 'vue-router', 'element-ui']
    },
    output: {
        path: path.join(__dirname, './static/js'), // 打包后文件输出的位置
        filename: '[name].dll.js',
        library: '[name]_library'
        // vendor.dll.js中暴露出的全局变量名。
        // 主要是给DllPlugin中的name使用,
        // 故这里需要和webpack.DllPlugin中的`name: '[name]_library',`保持一致。
    },
    plugins: [
        new webpack.DllPlugin({
            path: path.join(__dirname, '.', '[name]-manifest.json'),
            name: '[name]_library',
            context: __dirname
        }),
        // 压缩打包的文件,与该文章主线无关
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]
};
webpack --config ./webpack.dll.config.js
  • webpack.config.js
plugins: [
  new webpack.DllReferencePlugin({
    context: __dirname,
    manifest: require('./vendor-manifest.json')
  })
]
  • index.html
vim index.html

npm run build

Time: 3674ms

一些优化

  • index.html




  
  dll-test



  
  • webpack.config.js
cnpm i --save-dev html-webpack-plugin copy-webpack-plugin clean-webpack-plugin
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var CleanWebpackPlugin = require('clean-webpack-plugin')

output: {
  path: path.resolve(__dirname, './dist'),
  publicPath: '/',
  filename: 'build.[hash].js'
},

devServer: {
  historyApiFallback: true,
  noInfo: true,
  contentBase: path.join(__dirname, 'dist')
},

plugins: [
  new webpack.DllReferencePlugin({
    context: __dirname,
    manifest: require('./vendor-manifest.json')
  }),
  new HtmlWebpackPlugin({
    inject: true,
    template: './index.html',
    filename: 'index.html'
  }),
  new CopyWebpackPlugin([
    { from: 'static', to: 'static' }
  ]),
  new CleanWebpackPlugin(['dist'])
]
npm run dev

npm run build

小结

Improve Build Time Performance

参考

  • DllPlugin

  • webpack进阶——DllPlugin优化打包性能(基于vue-cli)

更多文章, 请支持我的个人博客

你可能感兴趣的:(web优化 之 DllPlugin)