Home >Web Front-end >JS Tutorial >Introduction to Webpack optimization configuration to narrow file search scope

Introduction to Webpack optimization configuration to narrow file search scope

不言
不言Original
2018-06-30 14:47:581788browse

This article mainly introduces the relevant knowledge of Webpack optimization-narrowing the file search scope. The article introduces the ways to optimize in more detail. Friends in need can refer to it

Webpack will start from Starting from the configured Entry, the import statements in the file are parsed, and then parsed recursively.

When encountering an import statement, Webpack will do two things:

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.

The following introduces ways to optimize them one by one.

Optimize loader configuration

Since the conversion operation of files by Loader is time-consuming, it is necessary to allow as few files as possible to be processed by 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.

Take 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'),
   },
  ]
 },
};

You can adjust the directory structure of the project appropriately to facilitate the include when configuring Loader. Reduce the hit area.

Optimize resolve.modules configuration

Introduced in 2-4 Resolve, resolve.modules is used to configure Webpack. Which directories to look for? Third party modules.

The default value of resolve.modules is ['node_modules'] , which means to first go to the ./node_modules directory in the current directory to find the module you are looking for. If it is not found, go to it. Search in the first-level directory ../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 module. To reduce searching, the configuration is as follows:

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

Optimize resolve.mainFields configuration

Introduced in 2-4 Resolve, resolve.mainFields is used Configure which entry file the third-party module uses.

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 entry file. description of.

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 as an example. It is an implementation of the fetch API, but can be used in both browser and Node.js environments.

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

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

isomorphic-fetch uses different codes in different running environments because the implementation mechanism of the fetch API is different. , implemented through native fetch or XMLHttpRequest in the browser, and implemented 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"]

  • When the target is other situations, the value is ["module", "main"]

Taking target equal to web as an example, Webpack will first use the browser field in the third-party module to find the module's entry file. If it does not exist, it will use the module field, and so on.

In order to reduce the search steps, when you specify the entry file description field of the third-party module, you can set it as little as possible.

Since most third-party modules use the main field to describe the location of the entry file, Webpack can be configured like this:

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

When using this method to optimize, you need to take into account all runtime dependencies. In the entry file description field of the third-party module, even if one module is wrong, the built code may not run normally.

Optimize resolve.alias configuration

Introduced in 2-4 Resolve, the resolve.alias configuration item maps the original import path through aliases into a new import path.

In actual projects, we often rely on some huge third-party modules. Taking the React library as an example, the directory structure of the React library installed in the node_modules directory is as follows:

├── 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'),
  }
 },
};

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

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

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

优化 resolve.extensions 配置

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

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

extensions: ['.js', '.json']

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

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

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

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

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

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

相关 Webpack 配置如下:

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

优化 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$/],
 },
};

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

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Webpack的dll功能的使用

Vue-cli proxyTable如何解决开发环境的跨域问题

The above is the detailed content of Introduction to Webpack optimization configuration to narrow file search scope. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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