性能优化笔记

229 阅读2分钟

webpack构建优化

最近看了修言大佬的性能优化小册,总结下记忆点

Dllplugin

使用Dllplugin将某些不经常升级的第三方库打包至一个单独文件中,这个文件就是一个单独的依赖库。这个依赖库不会跟着你的业务代码一起被打包,只有在你的依赖自身发生改变时才会重新打包。
使用:
1、设置Dll的配置文件,配置DLLPlugin,打包dll库

const path = require('path')
const webpack = require('webpack')

module.exports = {
    entry: {
        'bable-polyfill',
        'react',
        'react-dom',
        'react-router-dom'
    },
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].js',
        library: '[name]_[hash]'
    },
    plugins: [
        new webpack.DllPlugin({
            name: '[name]_[hash]',
            path: path.join(__dirname, 'dist', '[name]-manifest.json'),
            context: __dirname
        })
    ]
}

根据上面的配置,会打包出两个文件一个js、一个json。json文件记录的每个第三方依赖库打包后的具体路径。

{
  "name": "vendor_397f9e25e49947b8675d",
  "content": {
    "./node_modules/core-js/modules/_export.js": {
      "id": 0,
        "buildMeta": {
        "providedExports": true
      }
    },
    "./node_modules/prop-types/index.js": {
      "id": 1,
        "buildMeta": {
        "providedExports": true
      }
    },
    ...
  }
}

2、基于webpack.config.js,配置DllReferencePlugin

    //...webpack其他配置
    plugins: [
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./dist/vender-manifest.json')
        })
    ]

happypack

webpack是单线程任务,一个任务结束后才能进行下一个任务。happypack能把任务分解成多个子任务。并行去执行。
比如把babel过程交给happypack


const Happypack = require('happypack')
const os = require('os')
const happyThreadPool = Happypack.ThreadPool({ size: os.cpus().length })

module.exports = {
  module: {
    rules: [
      ...
      {
        test: /\.js$/,
        loader: 'happypack/loader?id=happyBabel',
        ...
      },
    ],
  },
  plugins: [
    ...
    new Happypack({
        id: 'happyBabel',
        threadPool: happyThreadPool,
        loaders: [{
            loader: 'babel-loader',
            options: babelConfig
        }]
    })
  ],
}


babel-loader缓存

babel过程很耗时,我们可以使用缓存,将编译结果缓存至文件系统,减少编译耗时。

    loader: 'babel-loader?cacheDirectory=true'

exclude的配置也必不可少。

    exclude: '/node_modules/'

tree-shaking(摇树优化)

基于import、export,webpack可以在编译过程中哪些模块没有被使用,在打包时去除冗余代码。

按需加载

常用的路由懒加载,import()
路由懒加载基于webpack的require.ensure方法。

    require(
        dependencies: Array
        callback: Function
        chunkName: String
    )

Gzip

前端使用Gzip,增加请求头accept-encoding: gzip;
Gzip的原理是处理文本文件中找出重复的字符,临时替换他们,从而减小体积。文件中重复率越高,压缩效率越高。