Home > Web Front-end > JS Tutorial > body text

How to optimize configuration files with Webpack

php中世界最好的语言
Release: 2018-04-13 15:06:47
Original
1279 people have browsed it

This time I will bring you how to optimize Webpackconfiguration file, what are the notes for optimizing the configuration file of Webpack, the following is a practical case, let's take a look.

After Webpack is started, it will start from the configured Entry, parse out the import statements in the file, and then parse them recursively.

Webpack will do two things when encountering an import statement:

1. Find the corresponding file to be imported according to the import statement. For example, the file corresponding to the require('react') import statement is ./node_modules/react/react.js, and the file corresponding to require('./util') is ./util.js.

2. Based on the found suffix of the file to be imported, use the Loader in the configuration to process the file. For example, JavaScript files developed using ES6 need to be processed using babel-loader.

Although the above two things are very fast for processing a file, when the project becomes large, the number of files will become very large, and the problem of slow build speed will be exposed.

Although the above two things cannot be avoided, they need to be minimized to increase speed.

Next, we will introduce ways to optimize them one by one.

Optimize loader configuration

Since the Loader's file conversion operation is time-consuming, it is necessary to allow as few files as possible to be processed by the Loader.

In 2-3 Module, we introduced that when using Loader, you can use the three configuration items test, include, and exclude to hit the files to which Loader wants to apply rules.

In order to allow as few files as possible to be processed by Loader, you can use include to target only which files need to be processed.

Taking a project using ES6 as an example, when configuring babel-loader, you can do this:

module.exports = {
 module: {
  rules: [
   {
    // 如果项目源码中只有 js 文件就不要写成 /\.jsx?$/,提升正则表达式性能
    test: /\.js$/,
    // babel-loader 支持缓存转换出的结果,通过 cacheDirectory 选项开启
    use: ['babel-loader?cacheDirectory'],
    // 只对项目根目录下的 src 目录中的文件采用 babel-loader
    include: path.resolve(dirname, 'src'),
   },
  ]
 },
};
Copy after login

You can appropriately adjust the directory structure of the project to facilitate narrowing the hit range through include when configuring Loader.

Optimize resolve.modules configuration

Introduced in 2-4 Resolve, resolve.modules is used to configure which directories Webpack searches for third-party modules.

The default value of resolve.modules is ['node_modules'] , which means first go to the ./node_modules directory in the current directory to find the module you are looking for. If not found, go to the upper-level directory ../ Search in node_modules, if not, search in ../../node_modules, and so on. This is very similar to the module search mechanism of Node.js.

When the installed third-party modules are placed in the ./node_modules directory in the project root directory, there is no need to search layer by layer in the default way. You can specify the absolute path to store the third-party modules to reduce searching. The configuration is as follows :

module.exports = {
 resolve: {
  // 使用绝对路径指明第三方模块存放的位置,以减少搜索步骤
  // 其中 dirname 表示当前工作目录,也就是项目根目录
  modules: [path.resolve(dirname, 'node_modules')]
 },
};
Copy after login

Optimize resolve.mainFields configuration

Introduced in 2-4 Resolve, resolve.mainFields is used to configure which entry file is used by the third-party module.

There will be a package.json file in the installed third-party module to describe the properties of the module. Some fields are used to describe where the entry file is. resolve.mainFields is used to configure which field is used as the description of the entry file.

The reason why there can be multiple fields describing the entry file is because some modules can be used in multiple environments at the same time, and different codes need to be used for different operating environments.

Take isomorphic-fetch, for example, which is an implementation of the fetch API but can be used in both browser and Node.js environments.

There are 2 entry file description fields in its package.json:

{
 "browser": "fetch-npm-browserify.js",
 "main": "fetch-npm-node.js"
}
Copy after login

Isomorphic-fetch uses different codes in different operating environments because the implementation mechanisms of the fetch API are different. It is implemented through native fetch or XMLHttpRequest in the browser, and through the http module in Node.js.

The default value of resolve.mainFields is related to the current target configuration. The corresponding relationship is as follows:

  • When the target is web or webworker, the value is ["browser", "module", "main"]

  • 当 target 为其它情况时,值是 ["module", "main"]

以 target 等于 web 为例,Webpack 会先采用第三方模块中的 browser 字段去寻找模块的入口文件,如果不存在就采用 module 字段,以此类推。

为了减少搜索步骤,在你明确第三方模块的入口文件描述字段时,你可以把它设置的尽量少。

由于大多数第三方模块都采用 main 字段去描述入口文件的位置,可以这样配置 Webpack:

module.exports = {
 resolve: {
  // 只采用 main 字段作为入口文件描述字段,以减少搜索步骤
  mainFields: ['main'],
 },
};
Copy after login

使用本方法优化时,你需要考虑到所有运行时依赖的第三方模块的入口文件描述字段,就算有一个模块搞错了都可能会造成构建出的代码无法正常运行。

优化 resolve.alias 配置

在 2-4 Resolve 中介绍过 resolve.alias 配置项通过别名来把原导入路径映射成一个新的导入路径。

在实战项目中经常会依赖一些庞大的第三方模块,以 React 库为例,安装到 node_modules 目录下的 React 库的目录结构如下:

├── dist
│   ├── react.js
│   └── react.min.js
├── lib
│   ... 还有几十个文件被忽略
│   ├── LinkedStateMixin.js
│   ├── createClass.js
│   └── React.js
├── package.json
└── react.js

可以看到发布出去的 React 库中包含两套代码:

  • 一套是采用 CommonJS 规范的模块化代码,这些文件都放在 lib 目录下,以 package.json 中指定的入口文件 react.js 为模块的入口。

  • 一套是把 React 所有相关的代码打包好的完整代码放到一个单独的文件中,这些代码没有采用模块化可以直接执行。其中 dist/react.js 是用于开发环境,里面包含检查和警告的代码。 dist/react.min.js 是用于线上环境,被最小化了。

默认情况下 Webpack 会从入口文件 ./node_modules/react/react.js 开始递归的解析和处理依赖的几十个文件,这会时一个耗时的操作。

通过配置 resolve.alias 可以让 Webpack 在处理 React 库时,直接使用单独完整的 react.min.js 文件,从而跳过耗时的递归解析操作。

相关 Webpack 配置如下:

module.exports = {
 resolve: {
  // 使用 alias 把导入 react 的语句换成直接使用单独完整的 react.min.js 文件,
  // 减少耗时的递归解析操作
  alias: {
   'react': path.resolve(dirname, './node_modules/react/dist/react.min.js'),
  }
 },
};
Copy after login

除了 React 库外,大多数库发布到 Npm 仓库中时都会包含打包好的完整文件,对于这些库你也可以对它们配置 alias。
但是对于有些库使用本优化方法后会影响到后面要讲的 使用 Tree-Shaking 去除无效代码 的优化,因为打包好的完整文件中有部分代码你的项目可能永远用不上。

一般对整体性比较强的库采用本方法优化,因为完整文件中的代码是一个整体,每一行都是不可或缺的。

但是对于一些工具类的库,例如 lodash ,你的项目可能只用到了其中几个工具函数,你就不能使用本方法去优化,因为这会导致你的输出代码中包含很多永远不会执行的代码。

优化 resolve.extensions 配置

在导入语句没带文件后缀时,Webpack 会自动带上后缀后去尝试询问文件是否存在。

在 2-4 Resolve 中介绍过 resolve.extensions 用于配置在尝试过程中用到的后缀列表,默认是:

extensions: ['.js', '.json']
Copy after login

也就是说当遇到 require('./data') 这样的导入语句时,Webpack 会先去寻找 ./data.js 文件,如果该文件不存在就去寻找 ./data.json 文件,如果还是找不到就报错。

如果这个列表越长,或者正确的后缀在越后面,就会造成尝试的次数越多,所以 resolve.extensions 的配置也会影响到构建的性能。

在配置 resolve.extensions 时你需要遵守以下几点,以做到尽可能的优化构建性能:

  • 后缀尝试列表要尽可能的小,不要把项目中不可能存在的情况写到后缀尝试列表中。

  • 频率出现最高的文件后缀要优先放在最前面,以做到尽快的退出寻找过程。

  • 在源码中写导入语句时,要尽可能的带上后缀,从而可以避免寻找过程。例如在你确定的情况下把 require('./data') 写成 require('./data.json') 。

相关 Webpack 配置如下:

module.exports = {
 resolve: {
  // 尽可能的减少后缀尝试的可能性
  extensions: ['js'],
 },
};
Copy after login

优化 module.noParse 配置

在 2-3 Module 中介绍过 module.noParse 配置项可以让 Webpack 忽略对部分没采用模块化的文件的递归解析处理,这样做的好处是能提高构建性能。

原因是一些库,例如 jQuery 、ChartJS, 它们庞大又没有采用模块化标准,让 Webpack 去解析这些文件耗时又没有意义。

在上面的 优化 resolve.alias 配置 中讲到单独完整的 react.min.js 文件就没有采用模块化,让我们来通过配置 module.noParse 忽略对 react.min.js 文件的递归解析处理,

相关 Webpack 配置如下:

const path = require('path');
module.exports = {
 module: {
  // 独完整的 `react.min.js` 文件就没有采用模块化,忽略对 `react.min.js` 文件的递归解析处理
  noParse: [/react\.min\.js$/],
 },
};
Copy after login

注意被忽略掉的文件里不应该包含 import 、 require 、 define 等模块化语句,不然会导致构建出的代码中包含无法在浏览器环境下执行的模块化语句。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

AngularJS实现猜数字小游戏

Angular实现可添加删除与计算总金额效果插件

The above is the detailed content of How to optimize configuration files with Webpack. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!