webpack的优化有哪些?

478 阅读1分钟

1、提取css为单独文件并压缩

1. const MiniCssExtractPlugin = require('mini-css-extract-plugin') //提取css引包

2. new MiniCssExtractPlugin({
        filename: 'css/main.css'
    })  //引入插件,规定css文件夹
    
3. { 
    test: /\.css$/, 
    use: [MiniCssExtractPlugin.loader, 
    'css-loader', 'postcss-loader']
    } //引入loader会分离css为单独文件
    
4. const OptimizeCss = require('optimize-css-assets-webpack-plugin') //压缩css

5. new OptimizeCss() //引入插件

2、压缩html和js

1. 压缩html
   new HtmlWebpackPlugin({
            template: './src/index.html', //生成内存模板
            filename: 'index.html',
            minify: { //压缩html
                removeAttributeQuotes: true,
                collapseWhitespace: true
            },
            hash: true
        })

2. 压缩js
    new UglifyJsPlugin({
        cache: true, //加缓存
        parallel: true, //并发打包
        sourceMap: true //源码映射
    })
    
3. 缓存
<!--js缓存-->
{
    test: /\.(js|jsx)$/,
    include: resolvePath('../src'),
    exclude: /node_modules(?!(\/|\\)bowser)/,
    loader: 'babel-loader',
    options: {
      cacheDirectory: true //js缓存
    }
  }
<!--css缓存-->
new MiniCssExtractPlugin({
    filename: 'css/main.[contenthash:8].css' //css缓存
}) 

3、tree shaking (去除无用代码)

  • 必须使用es6模块化
  • 开启production模式

4、代码分割

  • 抽离公共代码
  • 将入口文件和node_modules文件代码分离
  optimization: {
    splitChunks: {   //代码分割
      cacheGroups: {
        vendors: {
          test: /node_modules/, //抽离第三方模块,例如jquery
          chunks: 'all',
          name: 'vendors',
          priority: 2,
          enforce: true
        },
        app: {
          chunks: 'all', //抽离共同引入的文件
          name: 'app',
          minChunks: 5, //共同引入的次数多于5次
          minSize: 3000, //引入的体积
          priority: 1
        }
      }
    }

5、多线程打包

1. thread-loader
{
    test:/\.js/,
    use:[
    {
    loader:'thread-loader',
        options:{
            workers:2
        }
    }
    ]
}

2.happypack
let happypack = require('happypack');
{
    test: /\.js$/,
    use: 'happypack/loader?id=js'
}
new happypack({
    id: 'js',
    use: [
        {
            loader: 'babel-loader',
            options: { //用babel把es6转为es5
                presets: [
                    '@babel/preset-env'
                ],
                plugins: [
                    '@babel/plugin-proposal-class-properties'
                    // '@babel/plugin-transform-runtime'
                ]
            }
        }
    ]
}),

6、externals

  • 使用cdn,拒绝打包
index.html
<script src='xxxxxx.jquery.min.js'></script>

externals:{
    //拒绝jquery打包进来
    jquery:'jQuery'
}

7、dllplugin

  1. 新建webpack.dll.js
const webpack = require('webpack')
const path = require('path')

module.exports = {
  entry: {
    react: ['react', 'react-dom']
  },
  output: {
    library:  'react', // 以一个库的形式导出
    filename: '[name].dll.js'
  },
  plugins: [
    new webpack.DllPlugin({
      name: 'react',
      path: path.resolve(__dirname, 'dist/manifest.json')
    })
  ]
}
  1. package.json增加一个脚本

"dll": "webpack --config webpack.dll.js --mode=development"

3.动态链接

plugins: [
    new webpack.DllReferencePlugin({
      manifest: path.resolve(__dirname, 'dist/manifest.json')
    }),
    new AddAssetHtmlPlugin({ filepath: path.resolve(__dirname, 'dist/react.dll.js') })
  ]
  1. 用到了HTML引入静态资源的库

add-asset-html-webpack-plugin

8、减少查找

exclude:/node_modules/, 排除
include:path.resolve('src') 包含

9,ignoreplugin

new webpack.IgnorePlugin(/\.\/locale/,/moment/)

10、懒加载

  • react和vue都是使用同样的方法
import('xxxx').then(data=>{console.log(data)})