Home Web Front-end JS Tutorial Detailed example of Webpack optimization configuration to narrow the file search scope

Detailed example of Webpack optimization configuration to narrow the file search scope

Dec 25, 2017 pm 04:37 PM
web webpack Configuration

After Webpack is started, it will start from the configured Entry, parse out the import statements in the file, and then parse them recursively. 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 who need it can refer to it. I hope it can help everyone.

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'),
   },
  ]
 },
};
Copy after login

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

As 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 to 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 module. 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 third-party modules.

The installed third-party module will have a package.json file used to describe the properties of this 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"
}
Copy after login

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'],
 },
};
Copy after login

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 to a new import path through an alias.

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'),
  }
 },
};
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 等模块化语句,不然会导致构建出的代码中包含无法在浏览器环境下执行的模块化语句。

相关推荐:

Webpack实战之构建 Electron 应用实例详解

详解Webpack框架核心概念

webpack学习教程之前端性能优化总结

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The working principle and configuration method of GDM in Linux system The working principle and configuration method of GDM in Linux system Mar 01, 2024 pm 06:36 PM

Title: The working principle and configuration method of GDM in Linux systems In Linux operating systems, GDM (GNOMEDisplayManager) is a common display manager used to control graphical user interface (GUI) login and user session management. This article will introduce the working principle and configuration method of GDM, as well as provide specific code examples. 1. Working principle of GDM GDM is the display manager in the GNOME desktop environment. It is responsible for starting the X server and providing the login interface. The user enters

The perfect combination of PyCharm and PyTorch: detailed installation and configuration steps The perfect combination of PyCharm and PyTorch: detailed installation and configuration steps Feb 21, 2024 pm 12:00 PM

PyCharm is a powerful integrated development environment (IDE), and PyTorch is a popular open source framework in the field of deep learning. In the field of machine learning and deep learning, using PyCharm and PyTorch for development can greatly improve development efficiency and code quality. This article will introduce in detail how to install and configure PyTorch in PyCharm, and attach specific code examples to help readers better utilize the powerful functions of these two. Step 1: Install PyCharm and Python

Understand Linux Bashrc: functions, configuration and usage Understand Linux Bashrc: functions, configuration and usage Mar 20, 2024 pm 03:30 PM

Understanding Linux Bashrc: Function, Configuration and Usage In Linux systems, Bashrc (BourneAgainShellruncommands) is a very important configuration file, which contains various commands and settings that are automatically run when the system starts. The Bashrc file is usually located in the user's home directory and is a hidden file. Its function is to customize the Bashshell environment for the user. 1. Bashrc function setting environment

How to configure workgroup in win11 system How to configure workgroup in win11 system Feb 22, 2024 pm 09:50 PM

How to configure a workgroup in Win11 A workgroup is a way to connect multiple computers in a local area network, which allows files, printers, and other resources to be shared between computers. In Win11 system, configuring a workgroup is very simple, just follow the steps below. Step 1: Open the "Settings" application. First, click the "Start" button of the Win11 system, and then select the "Settings" application in the pop-up menu. You can also use the shortcut "Win+I" to open "Settings". Step 2: Select "System" In the Settings app, you will see multiple options. Please click the "System" option to enter the system settings page. Step 3: Select "About" In the "System" settings page, you will see multiple sub-options. Please click

How to configure and install FTPS in Linux system How to configure and install FTPS in Linux system Mar 20, 2024 pm 02:03 PM

Title: How to configure and install FTPS in Linux system, specific code examples are required. In Linux system, FTPS is a secure file transfer protocol. Compared with FTP, FTPS encrypts the transmitted data through TLS/SSL protocol, which improves Security of data transmission. In this article, we will introduce how to configure and install FTPS in a Linux system and provide specific code examples. Step 1: Install vsftpd Open the terminal and enter the following command to install vsftpd: sudo

MyBatis Generator configuration parameter interpretation and best practices MyBatis Generator configuration parameter interpretation and best practices Feb 23, 2024 am 09:51 AM

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

How to install and configure DRBD on CentOS7 system? Tutorial on implementing high availability and data redundancy! How to install and configure DRBD on CentOS7 system? Tutorial on implementing high availability and data redundancy! Feb 22, 2024 pm 02:13 PM

DRBD (DistributedReplicatedBlockDevice) is an open source solution for achieving data redundancy and high availability. Here is the tutorial to install and configure DRBD on CentOS7 system: Install DRBD: Open a terminal and log in to the CentOS7 system as administrator. Run the following command to install the DRBD package: sudoyuminstalldrbd Configure DRBD: Edit the DRBD configuration file (usually located in the /etc/drbd.d directory) to configure the settings for DRBD resources. For example, you can define the IP addresses, ports, and devices of the primary node and backup node. Make sure there is a network connection between the primary node and the backup node.

Flask installation and configuration tutorial: a tool to easily build Python web applications Flask installation and configuration tutorial: a tool to easily build Python web applications Feb 20, 2024 pm 11:12 PM

Flask installation and configuration tutorial: A tool to easily build Python Web applications, specific code examples are required. Introduction: With the increasing popularity of Python, Web development has become one of the necessary skills for Python programmers. To carry out web development in Python, we need to choose a suitable web framework. Among the many Python Web frameworks, Flask is a simple, easy-to-use and flexible framework that is favored by developers. This article will introduce the installation of Flask framework,

See all articles