webpack 构建提速

4 阅读1分钟

一文了解,目前webpack 构建提速 从webpack 构建流程

依赖解析提速

可以从文件解析路径以及别名,减少解析时间

// 3. 减少解析  
resolve: {  
// 指定扩展名,减少尝试  
extensions: ['.js', '.jsx','ts','tsx],

// 指定查找目录  
modules: [path.resolve('src'), 'node_modules'],

// 使用 alias 减少解析  
alias: {  
'@': path.resolve('src'),  
'react': path.resolve('node_modules/react')  
},

// 不解析的模块  
noParse: /lodash/  
},

从loader加载的角度--

可以配置exclude nodemoduels -官方库,默认会提供,编译后的,或者没有兼容需求

  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,

从多线程的角度

可以开启thread-loader 来进行多线程编译,提速,尽量最大限度复用cpu的多核能力

{
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'thread-loader',
            options: {
              workers: Math.max(os.cpus().length - 1, 1),
              workerParallelJobs: 50
            }
          },js
 

缓存的角度--

那么可以去开启systermcache - webpack5会自动化,缓存loader 转换后的文件,规避未改动文件的重复转换 首次打包构建后,会保存loader转换后的文件 下一次打包,会复用未改动文件的转换文件,实际提速,提速80%以上,效果显著

同时也要注意,这个,构建的产物失效,依据packagejson的改变会使缓存失效

  cache: {
    type: 'filesystem',
    cacheDirectory: path.resolve(__dirname, '../.webpack_cache'),
    buildDependencies: {
      config: [__filename, path.resolve(__dirname, '../package.json')]
    }
  }

懒编译

解决的是编译期的,延迟编译 懒加载解决的是运行时的模块加载,减少文件加载时间

  experiments: {
    lazyCompilation: {
      imports: true,
      entries: false
    }
  },
experiments: {
    lazyCompilation: {
      imports: true,
      entries: false
    }
  },js

开发环境禁用plugin 生产环境的

  if (env && env.analyze) {
  [(new BundleAnalyzerPlugin(),new TerserPlugin()].forEach((plugin)=>{config.plugins.push(plugin)})

  }