Everybody is good! I’m Radish. The last article introduced configuration related to Entry and output. This article will introduce other important configuration of Webpack.

resolve

The resolve configuration helps Webpack to find dependencies quickly. The resolve configuration helps Webpack to find dependencies quickly. You can also replace the corresponding dependencies (such as dev version lib for the development environment, etc.). The common Resolve configuration is described below.

1.resolve.extensions

Resolve. extensions is a configuration that helps Webpack resolve extensions. Default: [‘.wasm’, ‘.mjs’, ‘.js’, ‘.json’], so we can introduce js and json files without their extension, usually we can add.css,.less, etc., but make sure there are no CSS or JS files with the same name in the same directory. If so, write the entire path.

Module. Exports = {resolve: {extensions: ['. Js', '. Json ', '. CSS ']}}Copy the code
2. resolve.alias

Resolve. Alias is the most common configuration, and setting the alias helps WebPack find module dependencies faster and also makes it easier to write code. For example, in real development we often put all the source code in the SRC folder, which has the following structure:

The SRC ├ ─ ─ lib │ └ ─ ─ utils. Js └ ─ ─ pages └ ─ ─ demo └ ─ ─ index. JsCopy the code
To reference SRC /lib/utils.js in SRC /pages/demo/index.js, import utils from ‘.. /.. /lib/utils’, which gets ugly if the directory is deeper, can be shortened by setting alias, for example:

Module.exports = {SRC: path.resolve(__dirname, 'SRC'), '@lib' : path.resolve(__dirname, 'SRC /lib')}}Copy the code
With aliases set, we can use require(‘@lib/utils’) or require(‘ SRC /lib/utils’) to help Webpack locate modules in any file, regardless of the directory structure.

Tips: Alias names can be @! In practice, use one alias for special characters such as ~, or use one alias for different types. In this way, it can be distinguished from normal modules to increase identification.
3. resolve.mainFields

Some of the modules we use will provide several pieces of code for different hosting environments, such as ES5 and ES6, or browser and nodeJS. In this case, the package.json file will do the following configuration:

{' jsnext:main ':' es/index.js', // ES6 syntax entry file 'main' : 'lib/index.js', // ES5 syntax entry file, node' brower ': 'lib/web.js' // this is a browser version}Copy the code
In Webpack, the resolve. MainFields setting determines which version of the module code to use first. The default configuration of mainFields is as follows:

Module. exports = {resolve: {mainFields: [' brower ', 'main', 'jsnext:main]}}Copy the code
Webpack will search through the package.json file in the order in the array, using only the first file it finds. If we want to use the ES6 code first, we can configure it like this:

Module. exports = {resolve: {mainFields: [' jsnext:main, 'main', 'brower']}}Copy the code
The following are uncommon or simple configurations:

  • Resolve. mainFiles: The default file name for resolving a directory. The default file name is index.
  • Resolve. modules: Node_modules is the default when looking for module dependencies;
  • Resolve. Symlinks: Resolves compliant links (soft links, symlinks);
  • Resolve.plugins: Add parsing plugins, array format;
  • Resolve. CachePredicate: Whether or not to cache, Boolean and function are supported. Function passes an object with path and require, and must return Boolean.

module

As WebPack parses modules, different modules need to be handled using different types of module handlers, which are set up in the Module configuration. Module has two configurations: module.noParse and module.rules.

1. module.noParse 

The module.noParse configuration allows Webpack to ignore recursive parsing and processing of some unmodularated files. The benefit of this is to improve build performance by receiving a regular expression of type, or an array of regular expressions, or a function that receives a module path parameter:

Module. Exports = {module: {/ / noParse using regular expressions: / jquery | noParse loadsh / / / using functions: (content) => {// content represents the file path of a module // returntrueorfalse
            return/jquery|loadsh/.test(content); }}}Copy the code
Tips: Make sure that the excluded module code does not contain import, require, define, etc., to ensure that the webpack contains all modules, otherwise it will cause the packaged JS error due to the lack of modules.
2. Parser controls modular syntax

Because WebPack starts with modular JavaScript files, it has built-in parsing capabilities for modular JavaScript. Support AMD, Commonjs, SystemJs, ES6. The Parse property provides a more fine-grained configuration of which module syntax is parsed and which is not. If you set parser.commonjs to false, the module will not be parsed into the dependency and will not be processed by the commonJS require syntax.

The Module: {Rules: [{Test: / \. Js $/, Use: [' Babel - loader], Parser: {amd:false// Disable AMD CommonJS:false// Disable CommonJS system:false// Disable SystemJS harmony:false// Disable ES6 import/export
            requireInclude: false// Disable require.include requireEnsure:false, // Disable require. Ensure requireContext:false, // disable require.context requireJs:false// Disable requirejs browserrify:false// Disable browserify}}]}Copy the code
Tips: Parser is syntactically limited and noParse can only control which files are not parsed.
3.module.rules

Module. rules refers to submitting modules that meet the rule conditions to the corresponding processor for processing when processing modules, which is usually used to configure loader. Its type is an array, and each item in the array describes how to process part of files. Each rule can be roughly composed of the following three parts:

  • Conditional matching: Matches the module files to which rules can be applied by configuring test, include, and exclude.
  • Application rule: Use the use configuration item to apply the Loader to the module whose matching conditions pass. You can apply one Loader or a group of Loaders in the sequence from back to front. Of course, you can also pass different parameters to the corresponding Loader.
  • Resetting order: The default execution order of a group of Loaders is ** from back to front (or from right to left) **. Use enforce to place the execution order of one loader to the first (pre) or last (post).
4. Condition matching

As mentioned above, the configurations related to conditional matching are test, include, Exclude, Resource, resourceQuery, and issuer. Conditional matching objects include resource, resourceQuery, and issuer.

Resource: The absolute path of the request file. It has been resolved according to the resolve rule;

Issuer: Indicates the absolute path of the module file that requested the resource.

For example: import ‘./style.css? The inline ‘:

  • The resource is the/path/to/style.css. CSS;
  • ResourceQuery is? Inline after;
  • Issuer is/path/to/app. Js.
For example, the rule configuration item matches the following conditions: it comes from the SRC and test folders, does not contain node_modules and bower_modules subdirectories, and the file path of the module is a. TSX and. JSX file.

{
    test: \. JSX? $/, / \. TSX? $/], include: [path. Resolve (__dirname, 'SRC'), the path, resolve (__dirname, 'test')], exclude: [path.resolve(__dirname, 'node_modules'), path.resolve(__dirname,' brower_modules')]}Copy the code

Loader configuration

Loader is the parsing processor. Through Loader, we can convert JS of ES6 grammar into ES5 grammar, and transfer pictures into Base64 dataURL. Importing CSS and HTML directly from JavaScript files is also done using the corresponding loader.

We need to install the loader before using it. For example, if we want to introduce less in JavaScript, we need to install less-loader:

npm i -D less-loaderCopy the code
Then specify *.less in module.rules to use less-loader:

module.exports = {
    module: {
        rules: [
          test: /\.less$/.use: 'less-loader']}}Copy the code
Less $/ regex matches the module file to be processed with the less suffix and then passes it to less-loader, where less-loader is a string. Will eventually be used directly as an argument to require(). In this case, less files are processed by less-loader into corresponding CSS files.

1. The parameters of the Loader

There are two ways to pass parameters to loader:

  • Passed through options.
  • Passed in as a query.
// Pass module: {rules: [{test: /\.html$/, use: [{loader: 'html-loader', options: {minimize:true,
                removeComments: false,
                collapseWhitespace: false}}]}} // Pass module: {rules: [{test: /\.html$/, use: [{loader: 'html-loader?Minimize=true&removeComments=false&collapseWhitespace=false'}}}]]Copy the code

The Plugin plug-in

Plugin is an important part of Webpack. Plugin can solve problems that loader cannot solve. Webpack itself is there are a lot of plug-ins, so built a lot of plug-in, we can directly through the Webpack object attribute to directly use, example: Webpack. Optimize. UglifyJsPlugin

Module.exports = { // ... Plugins: [/ js/compression New webpack. Optimize. UglifyJsPlugin ()]}Copy the code
In addition to the built-in plug-ins, we can also use plug-ins through the NPM package:

// Non-default const ExtractTextPlugin = require(' extract-text-webpack-plugin ');Copy the code
Tips: Loader is designed to solve the problem of a module or a class of modules, while Plugin is designed to solve the problem of the whole project that loader cannot solve.

summary

In this chapter, the basic configuration items of Webpack except entry and output are explained. Here is a summary of the list of frequently configured and important configuration items for everyone to review:

  • Resolve: the module depends on finding the relevant configuration;
  • Resolve. Extensions: You can omit the resolver extension configuration. Too many resolvers will reduce the efficiency of WebPack parsing.
  • Resolve. Alias: Setting alias helps WebPack find module dependencies faster and simplifies writing relative paths when code is written.
  • Module. rules: loader-related configuration.
test: matches the module files to be processed. Use: loader array configuration, including loader and options. Include C. Exclude C.Copy the code
Plugins are plugins.