zl程序教程

您现在的位置是:首页 >  Java

当前栏目

webpack性能优化简要

2023-02-18 16:39:31 时间

1.优化loader的查找范围

  1. test: 匹配特定条件。一般是提供一个正则表达式或正则表达式的数组,但这不是强制的
  2. include(推荐): 匹配特定条件。一般是提供一个字符串或者字符串数组,但这不是强制的
  3. exclude(**优先级最高): ** 排除特定条件。一般是提供一个字符串或字符串数组,但这不是强制的
{
  test: /\.css$/,
  include: [
    path.resolve(__dirname, "app/styles"),
    path.resolve(__dirname, "vendor/styles")
  ]
}
优化方案

通过缩小模块的查找范围来减少查找时间

2.优化第三方模块的查找范围

  1. resolve.modules 解析模块时应该搜索的目录
module.exports={
  resolve:{
      modules: [path.resolve(__dirname, "./node_modules")]
  }
}
优化方案

通过指定解析模块的搜索目录来屏蔽调module向上查找增加的的耗时

3.优化导入模块目录层级多增加的耗时

  1. resolve.alias 通过配置别名来确保模块引入变得更简单
resolve: {
   alias: {
     "@": path.join(__dirname, "./pages"),
     "@assets": path.resolve(__dirname, "../src/images/"),
   },
},
优化方案:

通过使用别名(指明了目录/文件)来导入模块使得模块的递归解析时间缩短

4.优化导入模块未指明后缀增加的耗时

resolve.extensions

此配置在用户导入模块不携带后缀时会根据配置项中的后缀进行匹配查找

// v5.25.1版本默认值
extensions: [".js", ".json"]
优化方案
  1. 使用合理的后缀列表
  2. 导入模块时指明后缀5.使用多线程thread-loader 配置到耗时的loader中使得耗时loader可以在线程池中运行
安装 thread-loader:
npm install --save-dev thread-loader
用法:

把这个 loader 放置在其他 loader 之前, 放置在这个 loader 之后的 loader 就会在一个单独的 worker 池(worker pool)中运行

示例:
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve("src"),
        use: [
          "thread-loader",
          "expensive-loader"
        ]
      }
    ]
  }
}

6.使用缓存优化babel-loader

babel-loader 提供了  cacheDirectory 配置给 Babel 编译时给定的⽬录,并且将⽤于缓存加载器的结 果,但是这个设置默认是 false 关闭的状态,我们需要设置为 true ,这样 babel-loader 将使⽤默认的 缓存⽬录 。

安装 babel-loader:

webpack 3.x | babel-loader 8.x | babel 7.x

npm install babel-loader@8.0.0-beta.0 @babel/core @babel/preset-env webpack

webpack 3.x babel-loader 7.x | babel 6.x

npm install babel-loader babel-core babel-preset-env webpack
示例:
rules: [
  {
    test: /\.js$/,
    loader: 'babel-loader',
    options: {
        cacheDirectory: true
    },
  }
];

7.使用terser-webpack-plugin开启多线程和缓存

安装terser-webpack-plugin:
npm install terser-webpack-plugin --save-dev
示例:
const TerserPlugin = require('terser-webpack-plugin');
  module.exports = {
    optimization: {
      minimizer: [
        new TerserPlugin({
        cache: true, // 开启缓存
        parallel: true // 多线程
      })
    ]
  }
};

8.通过使用externals来减少依赖项> 防止将某些import的包打包到bundle中,而是在运行时去外部获取这些依赖

例如,从 CDN 引入 jQuery,而不是把它打包: index.html

<script
  src="https://code.jquery.com/jquery-3.1.0.js"
  integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
  crossorigin="anonymous">
</script>

webpack.config.js

externals: {
  jquery: 'jQuery'
}

依赖使用不变

import $ from 'jquery';
$('.my-element').animate(...);