webpack打包优化

分析打包结果

  1. 生成打包结果webpack –profile –json >stats.json
    将stats.json上传到analyse可视化

运行打包会自动打开一个本地网站

var BundleAnalyzerPlugin   = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

plugins: [
  new BundleAnalyzerPlugin()
]

优化打包速度

  • 区分第三方代码(vender)和业务代码(app)
// webpack.dll.conf.js
const path = require('path');
 const webpack = require('webpack')
 module.exports = {
  entry:{
    vue:['vue','vue-router'], // 第三方代码
    ui:['element-ui'] // 第三方代码
  },
  output:{
    path:path.join(__dirname,'./src/dll/'), //新建一个目录,存放dll文件
    filename:'[name].dll.js',
    library:'[name]', // 怎么引用打包好的第三方库
  },
  plugins:[
    new webpack.DllPlugin({
      path: path.join(__dirname,'./src/dll/','[name]-manifest.json'), // 打包后的dll文件放在位置及名称
      name:'[name]'
    }),
  ]
}

// webpack.pro.conf.js
plugin:[
    new webpack.DllReferencePlugin({
        manifest: require('./src/dll/ui-manifest.json')
    }),
    new webpack.DllReferencePlugin({
        manifest: require('./src/dll/vue-manifest.json')
    })
    ....
]

$_> webpack --config webpack.dll.conf.js
$_> webpack --config webpack.pro.conf.js

js文件中正常import 即可
  • UglifyjsWebpackPlugin
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
new UglifyJsPlugin({  parallel: true , cache: true}) //启用多线程和缓存
  • babel-loader:
 {
      test: /\.m?js$/,
      exclude: /(node_modules|bower_components)/, // 开启
      include: /js/,// 开启
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env'],
          cacheDirectory: true // 开启
        }
      }
    }
  • [使用happypack](
var HappyPack = require('happypack');
var happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });

module: {
  loaders: [
    {
      test: /\.js[x]?$/,
      include: [resolve('src')],
      exclude: /node_modules/,
      loader: 'happypack/loader?id=happybabel'
    }
  ]
},
plugins: [
  new HappyPack({
    id: 'happybabel',
    loaders: ['babel-loader'],
    threadPool: happyThreadPool,
    cache: true,
    verbose: true
  })
]
  • 减少resolve
  • devtool: 去除sourcemap
  • cache-loader: 将loader处理的结果缓存起来
  • 升级node和webpack

你可能感兴趣的:(webpack打包优化)