The basic use

1. Create a project

Create an empty directory (don’t name it webpack) as the project root directory and initialize the project by executing the following command on the command line to generate a package.json file:

npm init -y
Copy the code

2. Install webpack

Global installation (not recommended)

// Install webpack-cli // install webpack-cli NPM install webpack webpack-cli -g // Check the webpack -v // Uninstall NPM uninstall webpack webpack-cli -gCopy the code

Install webPack globally. This will lock webPack in your project to the specified version, causing conflicts in different projects because WebPack depends on different versions, causing build failures, so it is not recommended.

Partial installation (project installation)

Run the following command to partially install webPack related tools webpack and webpack-cli in your project.

// Install the latest stable version of NPM I webpack -d // Install the specified version of NPM I webpack@<version> -d // Install the latest experience version of NPM I webpack@<version> -d // Install the latest experience version of NPM I webpack@<version> -d // Do not use the production environment NPM I webpack@beta -d // When installing webPack V4+, Install webpack-cli NPM I webpack-cli -d // Install two NPM I webpack@<version> webpack-cli -d // For example install version 4.43.0: NPM I [email protected] webpack-cli -dCopy the code

Check the installation

Webpack -v// NPX looks for webpack./node_modules/.bin/webpack in project node_modules -v// Look for webPack in the current node_modulesCopy the code

3. Execute WebPack for the build

  • By default, WebPack only supports JS and JSON modules
  • supportcommonJS, es moudule, AMDEqual module type

3.1 Creating a project file

  • Create a SRC folder in the project root directory.
  • Create a new folder in the SRC folderindex.js,a.json,b.js.

In each of the three files, write:

### index.js const json = require("./a.json"); // commonJS import { demo } from "./b.js"; //es module console.log(json, demo(5, 3)); ### a.json { "name": "PYY" } ### b.js export function demo(x, y) { return x - y; }Copy the code

3.2 build

Method 1

You can get WebPack to convert the project code by using the following command:

npx webpack
Copy the code

Why use NPX? Since we do not have a global installation of Webpack, we will not find it if we use the webpack command directly. NPX will find the WebPack soft link in the bin directory of node-modules in the current project and launch it.

Way 2

In the package.json file scripts, add the command

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack"
 },
Copy the code

Then run the following command from the project root directory:

npm run dev
Copy the code

Again, go to the bin directory in Node-modules to find the Webpack soft link and launch it.

The principle of

The idea is to create a soft link in the node_modules/.bin directory using a shell script.

4. The construction is successful

We’ll find an additional dist directory with main.js, which is an executable JavaScript file that contains the webpackBootstrap launch function.

Hash: Indicates the Hash number of the version built this time.

Version: The Version number of this webpack

The main.js file is created with the chunks 0 and the chunk name main being 948 bytes in size

Warning: Mode option is not set. Set it to production or development. Default is Production.

Configuration webpack

1. Default Settings

By default, WebPack only supports JS and JSON files for packaging (the other two are not used).

The webPack configuration file is the webpack.config.js file in the project root directory. When we run the NPX webpack command, WebPack will automatically find the webpack.config.js file and use the configuration information to package. When we do not manually create the webpack.config.js file, the default configuration will be used.

const path = require("path"); Module. Exports = {// 1. {/ / deposit of the output file path, the path must be an absolute path path: the path. The resolve (__dirname, ". / dist "), / / will output all dependent module merge into the main, js, what is the name that is packed file filename: "main.js", }, // 3. Mode: "production", "production", "production", "none"};Copy the code

2. Change the default Settings

When we manually create the webpack.config.js file, the default configuration is invalid and our webpack.config.js file is left (without merging).

const path = require("path"); Module. Exports = {// 1. {// output file path must be absolute path: path.resolve(__dirname, "./build"), // output all dependent modules to main.js. "dist.js", }, // 3. Mode: "production", "production", "production"};Copy the code

3. Customize configuration files (not recommended)

Use –config to customize the configuration.

Create webpack.test.js in the config folder and write the following code:

const path = require("path"); Module. Exports = {// 1. {// output file path must be absolute path: path.resolve(__dirname, "./build1"), // output all dependent modules to main.js. "dist1.js", }, // 3. Mode: "production", "production", "production"};Copy the code

Add the command “start”: “webpack –config./config/webpack.test.js” to the scripts in pageage.json: “start”: “webpack –config.

Run NPM run start in the root directory

Core configuration of WebPack

entry

Entry specifies the entry into which WebPack is packaged: The first step in WebPack’s execution of a build starts with an entry, which can be abstracted into input.

Entry has three types: string, array, and object.

  • entry: “./src/index.js”,

    {“main”: “./ SRC /index.js”}

    Note: bundle: 1 bundle file containing chunks of index.js code

  • Entry: [“./ SRC /b.js”, “./ SRC /index.js”, “./ SRC/a.jaxon “], note: bundle: 1 bundle file that contains the a.js segment and the B.JS segment, finally integrating the two segments.

  • / SRC /index.js', // bundle entry a: './ SRC/a.jaxon ', // a entry b: './ SRC /b.js' // b entry}, // the value of filename needs to be changed to "[name].js", [name] corresponds to the key placeholder bundle filenameCopy the code

Single entry: string, array

Multiple entries: Object object.

A.jaxon, B.js, and index.js are modules, which eventually result in chunks of code.

The code fragment generated by the index.js module is chunk Index A. Johnson module. The code fragment generated by the module is chunk A B. JS module. The code fragment generated by the module is chunk B A chunk is a chunk of code in an eval() packageCopy the code

Is the connection between mode Entry Output Module chunks Bundles?

output

Package the converted file and output it to disk location: Output the result, which is typed after Webpack has gone through a series of processes to arrive at the desired code

Out of the results.

Output: {filename: "bundle.js",// output filename path: Path.resolve (__dirname, "dist")// Output file to disk directory, must be absolute path}, // multi-entry processing output: {filename: Path: path.resolve(__dirname, "dist")// Output file to disk directory, must be absolute path}, output: {filename: "js/[name][chunkhash:8].js",// put the js code in the js folder path: path.resolve(__dirname, "dist"), publicPath: // Add the URL (CDN address) to the output resource file, so we don't have to add the server address to the static resource ourselves. However, it is important to note that we need to upload the file to the CDN server and only affect HTML. },Copy the code

mode

The Mode command specifies the current build environment

  • production
  • development
  • none

Setting mode automatically triggers webPack’s built-in functions to achieve optimized results.

The opening of the development phase will facilitate the processing of hot updates to identify which modules have changed.

The start of the production phase will help with module compression, handling side effects and other functions.

loader

Module parsing, module converter, used to convert the original content of the module into new content as required.

Since WebPack itself can only package JS and JSON code, it means that when we use CSS, less, Sass, JSX and other code that cannot be recognized by the browser in our project, WebPack cannot process these code by default. So at this point, we need to introduce some other tools into WebPack. These tools, we call “loaders.” Notice the loader order: value or execution from right to left (or bottom to top)

Common loaders:

Style-loader CSS -loader less-loader sass-loader ts-loader // Convert TS to JS Babel - Loader // Convert ES6, 7 and other JS new feature syntax file-loader// Processing images eslint-loader // eslint ...Copy the code

The configuration of loaders

All loaders are configured in the module.rules array:

module: {
    rules: []}Copy the code
CSS Packaging Configuration

When we just download and install the CSS-Loader, the introduction is not effective, because it is essentially CSS in JS, extracting the CSS code as strings into the bundle file, so the browser does not parse into the CSS. So you also need a styleloader to extract the CSS string from the bundle, create a style tag in the header of the HTML, and put the CSS string inside the style so that the browser can read and parse it into the CSS.

Download the loaders
npm i style-loader css-loader -D
Copy the code
Configuration loaders
module: {
    rules: [
        / / packaging CSS
        {
            // test is used to configure the file name to be matched by the current packing rule
            test: /\.css$/i.// use Is used to configure the loader used by the current packing rule
            // When multiple loaders are needed to process a module, an array is required
            // Order of execution: from the back to the front
            // Loader does only one thing
            // Loader-style: loader-style: loader-style: loader-style
             use: ['style-loader'.'css-loader']
            //use: {
            // loader: 'css-loader'
            / /}}}]Copy the code
Less Packaging Configuration
Download the loaders
npm i less less-loader -D
Copy the code
Configuration loaders
{
    test: /\.less$/i,
    use: ['style-loader'.'css-loader'.'less-loader'].exclude: /node_modules/,}Copy the code

Note: If this. GetOptions is not a function is displayed, it is because the version of less-loader is too high and cannot be compatible.

NPM uninstall less-loader NPM install [email protected]Copy the code
SCSS packaging configuration
Download the loaders
npm i node-sass sass-loader -D

npm i node-sass -D --sass_binary_site=https://npm.taobao.org/mirrors/node-sass/ 
Copy the code
Configuration loaders
{
    test: /\.scss/i,
    use: ['style-loader'.'css-loader'.'sass-loader'].exclude: /node_modules/,}Copy the code

The plugins plugin

Plug-in: a mechanism that acts on the entire WebPack packaging lifecycle.

Each plug-in aligns with a lifecycle, such as before packaging, before resource file generation, after resource file generation, and so on.

Plugins can do things for you when WebPack reaches a certain stage, similar to the concept of a lifecycle

Extensions that inject extension logic at specific times in the Webpack build process to change the build result or do what you want. Applies to the entire build process.

Plugins Basic configuration of plugins

module.exports = {
    // Plug-in configuration
    plugins: []}Copy the code
html-webpack-plugin

Htmlwebpackplugin will automatically generate an HTML file after packaging, and introduce the generated JS module into the HTML.

download
npm i html-webpack-plugin -D
Copy the code
The introduction of
const HtmlWebpackPlugin = require('html-webpack-plugin');
Copy the code
Configured to use
module.exports = {
    // Plug-in configuration
    plugins: [
	new HtmlWebpackPlugin({
            template: './index.html'./ / template
            filename: 'index.html'.// The name of the generated HTML
            chunks: ['index'] // Which js to load}})]Copy the code

Configuration description:

Title: the title element used to generate the page filename: the output HTML filename, which defaults to index.html and can also be configured directly with subdirectories. Template: Path to a template file that supports loaders such as HTML! ./index.html inject: True | 'head' | 'body' | false, the injection of all the resources to a specific template or templateContent, if set to true or body, All javascript resources will be placed at the bottom of the body element, and 'head' will be placed inside the head element. Favicon: Adds a specific Favicon path to the output HTML file. Minify: {} | false, pass HTML - minifier option to minify the hash output: True | false, if true, will add a unique webpack compile hash to contain all scripts and CSS files, to remove the cache is very useful. Cache: true | false, if true, this is the default value, just won't be published file after file modification. ShowErrors: true | false, if true, this is the default value, the error message will be written to the HTML page chunks: allow only add some pieces (for example, unit test piece only) chunksSortMode: Allows the control block is added to the page before the sort of way, support value: 'none' | 'default' | {function} - the default: 'auto' excludeChunks: allowed to skip certain block, block (for example, skip the unit tests)Copy the code
clean-webpack-plugin

Clear unwanted files from the package.

download
npm i clean-webpack-plugin -D
Copy the code
The introduction of
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
Copy the code
Configured to use
module.exports = {
    // Plug-in configuration
    plugins: [
        new CleanWebpackPlugin()
    ]
}
Copy the code
mini-css-extract-plugin

As mentioned earlier, styleloader dynamically generates THE CSS and packages it directly into JS, but we want to generate the CSS file separately, because it can be downloaded in parallel with JS to improve page loading efficiency. The disadvantage is that it will increase the number of requests.

download
npm i mini-css-extract-plugin -D
Copy the code
The introduction of
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
Copy the code
Configured to use
module.exports = {
    module: {
        rules: [
            / / packaging CSS
            {
                // test is used to configure the file name to be matched by the current packing rule
                test: /\.less$/.// use Is used to configure the loader used by the current packing rule
                / / use MiniCssExtractPlugin. Loader to replace style - loader
                // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
                // use: [ MiniCssExtractPlugin.loader, 'css-loader', "postcss-loader", 'less-loader'],
                use: [ {
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        publicPath: '.. / '}},'css-loader'."postcss-loader".'less-loader'].// include is used to introduce modules that meet any of the following criteria
                include: path.resolve(__dirname, './src')},]},plugins: [
        new MiniCssExtractPlugin({
             filename: "css/[name]_[contenthash:4].css".chunkFilename: "[id].css"}})]Copy the code

moudle

Everything in Node is a module. Webpack is node based. A module corresponds to a file. Webpack will recursively find all dependent modules from the configured Entry.

When webPack processes an unknown module, you need to configure the Module in WebPack, and when the module format is detected, which loader is used to process the module.

Module :{rules:[{test:/\.xxx$/,// Use :{loader: 'xxx-load'// Use :{loader: 'xxx-load'}}]}Copy the code

file-loader

File-loader, which handles static resource modules. The idea is to move the resource module identified in the package entry to the output directory and return an address name.

So when do we use file-loader?

Scenario: When we need a module, just move from the source code to the package directory, we can use file-Loader to process, TXT, SVG, CSV, Excel, image resources, etc

Install: NPM install file-loader -dCopy the code
Use: the module: {rules: [{test: / \ | GIF (PNG | jpe? G) $/, / / use the use of a loader can use object, string, two loader need to use an array to use: {loader: "File-loader ", // options Additional configuration, such as resource name options: {/ / placeholder placeholder [name] old resources module name / / / ext old resources module of the suffix name: / / https://webpack.js.org/loaders/file-loader#placeholders "[name] _ [hash] [ext]", / / the location after packaging outputPath: "images /]}}}}"Copy the code

Style handling:

Css-loader analyzes the relationships between CSS modules and synthesizes a CSS

Loader Execution order: from back to front

The style-loader will then mount the content generated by the CSS-Loader to the heade section of the page in Style

npm install style-loader css-loader -D
Copy the code
{ test: /\.css$/, use: ["style-loader", "css-loader"] } { test: /\.css$/, use: [{ loader: "style-loader", options: {injectType: "singletonStyleTag" // Merge all style tags into one}}, "css-loader"]}Copy the code

Production, development mode to distinguish packaging

Use the webpack-merge plug-in

Installation:

npm install webpack-merge -D
Copy the code

Split the configuration into a basic configuration, a development configuration, a production configuration, and then merge the configuration via webpack-merge.

Use:

const { merge } = require('webpack-merge'); // The latest version requires this to take the merge function const commonConfig = require('./ webpack.mon.js '); const proConfig = { mode: 'production', module: { // xxxxx }, plugins: { // xxxxx } } module.exports = merge(commonConfig, proConfig);Copy the code

Modify the package.json file:

"dev": "webpack-dev-server --config ./build/webpack.dev.js",
"build": "webpack --config ./build/webpack.pro.js",
"start": "npm run dev"
Copy the code

Note: In a development environment, an error will be reported when using chunkhash for an image. Hash is recommended.

cross-env

Installation:

npm i cross-env -D
Copy the code

Modify the package.json file:

"dev": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.dev.js",
"build": "cross-env NODE_ENV=production webpack --config ./build/webpack.pro.js",
"start": "npm run dev"
Copy the code

Access to:

In each configuration file, the parameters can be obtained by process.env.node_env.

Other plug-ins

WebpackDevServer

WebpackDevServer can help us automatically package and refresh pages, which can improve development efficiency.

Installation:

npm i webpack-dev-server -D
Copy the code

Modify the package. The json

"scripts": {
    // xxx
    "server": "webpack-dev-server"
 },
Copy the code

In webpack.config.js configure:

devServer: { contentBase: path.resolve(__dirname, '.. /dist'), // By default, the local server will be provided as the root folder, where the specified folder (pointing to the static resource directory) is inline: true, // Automatically refresh hot: true, // enable the hot module to replace historyApiFallback: True, // useful when developing single-page applications, it relies on the HTML5 History API. If set to true, all jumps will point to index.html open: PublicPath: '/', compress: true, // Stats: 'minimal', port: 8080 // Port number, default is 8080},Copy the code

Activation:

npm run server
Copy the code

During startup, the following error may occur:

 Cannot find module 'webpack-cli/bin/config-yargs'
Copy the code

Webpack-cli @^4.3.0 conflicts with webpack-dev-server@^3.11.0. The webpack-cli version needs to be reduced to 3.x version:

npm uninstall webpack-cli
npm i webpack-cli@3 -D
Copy the code

After the earlier version is downloaded, run the NPM run server command again to start the server.

After starting the service successfully, you will find that the files in dist are gone, because devServer keeps the packaged modules not in the dist directory, but in memory to speed things up.

devtool

The mapping between the source code and the packaged code can be configured to locate the specific source code. For example, there is an error in the code, so we can locate the specific place to view

Devtool website address:

  • Source-map: generates the. Map file
  • Cheap: contains only row information but not column information. In other words, it locates a specific row, but does not show which column it is.
  • Module: sourcemap (third-party Module) containing loader
  • Eval: Use eval to wrap module code (fastest)

Add:

devtool: 'cheap-source-map',
Copy the code

Then run the restart command NPM run dev again to start the server.

In a development environment, the official recommended configuration is cheap-eval-modul -source-map.

The code address

Github address: