1. Concept
Need to understandFour core concepts:
- Entry
- Output
- loader
- Plugins
1. Entrance
1.1 Basic concepts
Specifies which module webpack starts with as the start of project construction.
By configurationentry
Properties, specify one or more starting points, default value./src
:
= { entry: './path/leo/' };
1.2 Single file entry
usage:entry: string|Array
whenentry
The name of the file object with no configuration entry is used by defaultmain
Name, output is,Right now:
// Default = { entry: './path/leo/' }; // Configure a single entryconst config = { entry: { main: './path/leo/' } };
It can be seen that in factDefaultonlyConfigure a single entryabbreviation form of .
in addition,File pathWe can also pass in an array and inject multiple dependency files together:
const config = { entry: { main: ['./path/leo/', './path/leo/', './path/leo/'] } };
1.3 Multi-file entry
usage:entry: {[entryChunkName: string]: string|Array}
Multiple filesCompletely separated,Independent of each other(Each bundle has a webpack bootstrap), which is commonly found in single-page applications with only one entry.
const config = { entry: { app: './src/', vendors: './src/' } };
2. Export
2.1 Basic concepts
Specify the final output file output location and file name of webpack.
By configurationoutput
Attribute, specify the output location and file name, the default output location is./dist
:
Two attributes:
-
path
: The output directory absolute path; -
filename
: The output file name;
const path = require('path'); = { entry: './path/leo/', output: { path: (__dirname, 'dist'), filename: '' } };
2.2 Use placeholders to name each file to ensure that the name is unique
output: { path: (__dirname, 'dist'), filename: '[name].js' }
2.3 Using CDN and resource hash
output: { path: "/home/proj/cdn/assets/[hash]", publicPath: "/assets/[hash]/" }
If you do not know the publicPath of the final file during compilation, you can leave it blank and set it dynamically in the entry file. Or set __webpack_public_path__ at the entry start point to ignore it.
__webpack_public_path__ = myRuntimePublicPath
3. loader
3.1 Basic concepts
Enable webpack to handle non-JS files,import
or preprocess files when "loading" the module.
Implementation by configuring two properties of loader:
-
test
Attributes used to identify one or more files that should be converted by the corresponding loader; -
use
Attributes, which loader to use during conversion;
const path = require('path'); const config = { output: { filename: '' }, module: { rules: [ { test: /\.txt$/, use: 'raw-loader' } ] } }; = config;
3.2 Install and use loader
If installing onecss-loader
andts-loader
Make webpack load CSS files, orTypeScript
Convert toJavaScript
:
npm install --save-dev css-loader ts-loader
use:
// = { module: { rules: [ { test: /\.css$/, use: 'css-loader' }, { test: /\.ts$/, use: 'ts-loader' } ] } };
3.3 Three ways to use loader
- Configuration (recommended): Specify loader in the file.
Specify multiple loaders:
module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { modules: true } } ] } ] }
- Inline: explicitly specify the loader in each import statement.
Can be inimport
Sentence or any equivalent toimport
Specify the loader in the method, use!
Separate multiple loaders, each part being a parsing relative to the current directory.
import Styles from 'style-loader!css-loader?modules!./';
Use as much as possible, reduce the amount of code, and debug and locate issues in loader faster in the event of errors.
- CLI: Specify them in the shell command.
webpack --module-bind jade-loader --module-bind 'css=style-loader!css-loader'
3.4 Loader loading order
The loader will start from the last array and load one by one:
// = { module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, ] } };
3.5 loader features
- loader supports chained delivery.
- Able to use pipelines for resources. A set of chain loaders will be executed in the reverse order. The first loader in the loader chain returns the value to the next loader. In the last loader, return the JavaScript expected by webpack.
- The loader can be synchronous or asynchronous.
- The loader is running in , and is able to perform any possible operations.
- loader receives query parameters. Used to pass configuration to loader.
- The loader can also be configured using the options object.
- In addition to using the common main attribute, you can also export the ordinary npm module as a loader, by defining a loader field in it.
- Plugins can bring more features to loaders.
- The loader can generate any additional arbitrary files.
4. Plug-in
4.1 Basic concepts
Let webpack perform more tasks, fromOptimization and compression,arriveRedefine variables in the environment, very powerful.
The purpose of the plug-in is to solve other things that cannot be achieved by loader.
When using it, just needrequire
It, and add toplugins
Array, bynew
Just instantiate:
const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install const webpack via npm = require('webpack'); // Used to access built-in plug-ins const config = { module: { rules: [ { test: /\.txt$/, use: 'raw-loader' } ] }, plugins: [ new HtmlWebpackPlugin({template: './src/'}) ]}; = config;
4.2 Core Knowledge
Principle analysis:
The webpack plugin is aapply
JavaScript object of attributes.apply
Attributes will bewebpack compiler
Called, andcompiler
The object canAccess throughout the compilation lifecycle。
usage:
Because the plug-in can be carriedparameter/Options, you have to be inwebpack
In configuration,plugins
Attributes are passednew
Example.
Configuration:
// const HtmlWebpackPlugin = require('html-webpack-plugin'); //Installation via npmconst webpack = require('webpack'); //Access the built-in plug-inconst path = require('path'); const config = { entry: './path/leo/', output: { filename: '', path: (__dirname, 'dist') }, module: { rules: [ { test: /\.(js|jsx)$/, use: 'babel-loader' } ] }, plugins: [ new (), new HtmlWebpackPlugin({template: './src/'}) ] }; = config;
5. Mode
By configurationmode
Parameters, specify the current development model, there isdevelopment
andproduction
Two values:
= { mode: 'production' };
It can also be passed through CLI parameters:
webpack --mode=production
Parameter description:
Options | describe |
---|---|
development | The value of .NODE_ENV will be set to development. Enable NamedChunksPlugin and NamedModulesPlugin. |
production | The value of .NODE_ENV will be set to production. Enable FlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and UglifyJsPlugin. |
Remember, if you only set NODE_ENV, mode will not be automatically set.
2. Configuration
The configuration file of webpack is a JavaScript file that exports an object, which is parsed by webpack based on the attributes defined by the object.
Because webpack configuration is a standard CommonJS module, you can do the following:
- pass
require(...)
Import other files; - pass
require(...)
usenpm
tool function; - Use JavaScript to control flow expressions, e.g.
?:
Operator; - Use constants or variables for common values;
- Write and execute functions to generate partial configuration;
But the following practices should be avoided:
- When using the webpack command line interface (CLI) (you should write your own command line interface (CLI), or use
--env
) when accessing the command line interface (CLI) parameters; - Exporting uncertain values (calling webpack twice should produce the same output file);
- Write long configurations (the configuration should be split into multiple files);
1. Basic configuration
// var path = require('path'); = { mode: 'development', entry: './', output: { path: (__dirname, 'dist'), filename: '' } };
2. Multiple configurations
In addition to single configuration objects everywhere, we can also have some other ways:
2.1 Export as a function
We may need to consider bothDevelopment EnvironmentandProduction environment,existWe will have at least two ways to implement it:
- Export oneConfiguration Objectsto replace;
- Export oneParameters can be passedFunction:
Pass in two parameters: environment variable (View environment options for CLI documentation) and map objects (argv
)parameter.
= function(env, argv) { return { mode: ? 'production' : 'development', devtool: ? 'source-maps' : 'eval', plugins: [ new ({ compress: argv['optimize-minimize'] // Only pass in -p or --optimize-minimize }) ] }; };
2.2 Export as a Promise
webpack will run the function exported by the configuration file and waitPromise
return. It facilitates the need for asynchronous loading of required configuration variables.
= () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ entry: './', /* ... */ }) }, 5000) }) }
2.3 Export multiple configuration objects
We set the export object into an array, and when the webpack runs, all configuration objects will be built, which is very useful for packaging a library for multiple build targets such as AMD and CommonJS.
= [{ output: { filename: './', libraryTarget: 'amd' }, entry: './', mode: 'production', }, { output: { filename: './', libraryTarget: 'commonjs' }, entry: './', mode: 'production', }]
3. Use other configuration languages
webpack accepts configuration files written in a variety of programming and data languages. The supported file extension list can be found innode-interpretFound in the package. usenode-interpret, webpack can handle many different types of configuration files.
Document introduction:"Configuration languages"
3.1 TypeScript
In order to write webpack configuration files in TypeScript, the relevant dependencies must be installed first:
npm install --save-dev typescript ts-node @types/node @types/webpack
Use TypeScript to write a configuration file for webpack:
// import path from 'path'; import webpack from 'webpack'; const config: = { mode: 'production', entry: './', output: { path: (__dirname, 'dist'), filename: '' } }; export default config;
3.2 Babel and JSX
In the following example,JSX
(React
Form of javascript) andBabel
Come to createJSON
Form webpack configuration file:
First install the dependencies:
npm install --save-dev babel-register jsxobj babel-preset-es2015
Setting configuration:
// .babelrc { "presets": [ "es2015" ] } // import jsxobj from 'jsxobj'; // example of an imported plugin const CustomPlugin = config => ({ ...config, name: 'custom-plugin' }); export default ( );
3. Module
1. Module introduction
During development, the program is decomposed into discrete functional blocks and becomes a module.
The webpack module can express their dependencies in various forms:
- es6:
import
statement; - CommonJS:
require()
Sentence; - AMD:
define
andrequire
Sentence; -
css/sass/less
in the file@import
Sentence; - style(
url(...)
) or image link in HTML file (image url
);
See moreModule method。
2. Module analysis
useresolver
The library will find the absolute path to the module and help webpack find the module code that needs to be introduced in the bundle. These codes are included in eachrequire
/ import
In the statement, in the module packaging, webpack usesenhanced-resolveTo parse the file path
webpack parsing rules:useenhanced-resolve
,webpack
Support parsing three file paths:
- Absolute path:
import "/home/me/file"; import "C:\\Users\\me\\file";
- Relative path:
import "../src/file1"; import "./file2";
- Module path:
import "module"; import "module/lib/file";
The module will be inSearch in all directories specified in , and can also be used
Initialize the module path.
The resolver checks whether the path points to a file or directory, if it points to a file:
- If there is a file extension, package it directly;
- Otherwise use [
] option is used as file extension to resolve, and configure which extensions the parser can accept during parsing (for example,
.js
,.jsx
)。
If it is pointing to a folder, follow the steps to find the file with the correct extension name:
- If the folder contains
Files, search in orderFields specified in the configuration options. And
The first such field in determines the file path.
- If it does not exist
File or
in the file
main
The field does not return a valid path, so it is searched in order.The file name specified in the configuration options depends on whether it can be found in
import/require
A file name that exists is matched in the directory. - File extension pass
The options are parsed using a similar method.
3. Analyze the loader
Loader parsing follows the same rules as those specified by the file parser. butresolveLoader
Configuration options can be used to provide independent parsing rules for Loader.
4. Cache
Each file system access is cached to trigger multiple parallel or serial requests to the same file faster. existObservation modeNext, only modified files will be extracted from the cache. If you turn off the watch mode, clean the cache before each compilation.
For more information about the above configurations, please checkAnalytics APIstudy.
IV. Construction goals
Note: webpack'starget
Don't be attributedAttribute confusion.
1. Usage
Set it in your webpack configurationtarget
Value:
= { target: 'node' };
In the above example, usenode
webpack will be compiled for use in "class" environment (usingrequire
, instead of using any built-in module (such asfs
orpath
) to load chunk).
For more detailed values, please refer toTargets
2. Multiple targets
Although webpack does not supporttarget
Passing in multiple strings, you can create isomorphic libraries by packing two separate configurations:
var path = require('path'); var serverConfig = { target: 'node', output: { path: (__dirname, 'dist'), filename: '' } //… }; var clientConfig = { target: 'web', // <=== The default is 'web', which can be omitted output: { path: (__dirname, 'dist'), filename: '' } //… }; = [ serverConfig, clientConfig ];
This is all about this article about the core concept of Webpack. I hope it will be helpful to everyone's learning and I hope everyone will support me more.