This is a series of articles on the basics of WebPack configuration, such as images, HTML, other resource configuration, DevServer configuration, environment configuration. In this article, I will also briefly describe the working mode of Webpack, the construction process, and the differences between Loader and Plugin. Such as knowledge; Encountered pits, problems to share;

Official start:

Prepare the skills

Basic NodeJS knowledge and NPM instructions

Note: the webpack version used in this series is: “webpack”: “^5.68.0”,

“Webpack – cli” : “^ 4.9.2”,

Front knowledge

One of the problems left in the last post is that we want to automatically generate HTML, otherwise we have to delete the build folder every time, we have to manually create the index.html file, too troublesome

Plugin

The concept of Plugin was briefly introduced in the previous basic concepts article.

Plugins: Extensions that inject extension logic at specific points in the Webpack build process to change the build result or do what you want. Can be used to perform a wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment.

Plugins configuration:
  • 1. Download the module
  • 2, the introduction of
  • 3, use,

Summary: To use a plugin, install and download the plugin, require() it, and add it to the plugins array. Most plug-ins can be customized with options. You can also use the same plug-in multiple times for different purposes in a configuration file by using the new operator to create an instance of the plug-in.

Package HTML resources – Automatically produce HTML

We want to automatically generate HTML files and import the generated resources into them

1. Download the module

npm i html-webpack-plugin -D
Copy the code

2, the introduction of

const HtmlWebpackPlugin = require('html-webpack-plugin')
Copy the code

3, use,

plugins: [// function: New HtmlWebpackPlugin({// Copy './index.html') {// Copy './index.html' Template: './index.html' // // specifies the template file}),]Copy the code

The attributes in’ html-webpack-plugin’ are:

  • Minify compresses HTML files. RemoveAttrubuteQuotes remove double quotes from attributes
  • Hash is used to import output resources with a query parameter. The value is hashed to avoid caching
  • Template template path
  • Filename Specifies the name of the output file
  • ChunksSortMode :’manual’// Mode for sorting incoming code blocks
  • Which area of HTML the inject packed resource is imported into, we can see that the default is loaded

4. Create index.html in the root directory

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <div id="title">Copy the code

5. Run WebPack

Look at index.html in the Build folder

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> <script defer SRC ="built.js"></script></head> <body> <div </div> </body> </ HTML >Copy the code

We can see the auto-add

<script defer src="built.js"></script>
Copy the code

It’s also normal to check your browser.

Image Resource Configuration

1. Create assets/images folder under SRC. This folder is to store some image resources

2. Then modify the index. HTML and add three div boxes with sizes 100px, 200px and 300px and fill the background with images

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <div id="title">webpack5 knowledge </div> <hr> <div class="box box1"></div> <hr> <div class="box box2"></div> <hr> <div class="box box3"></div> <hr> </body> </html>Copy the code

3. Background image introduction: modify index.less

#title{ color: chocolate; } .box{ border: 1px saddlebrown solid; background-size: 100%; background-repeat: no-repeat; &.box1{ width: 100px; height: 100px; background-image: url('./assets/images/vite.png'); } &.box2{ width: 200px; height: 200px; background-image: url('./assets/images/webpack.jpg'); } &.box3{ width: 300px; height: 300px; background-image: url('./assets/images/zx.png'); }}Copy the code

Run webpack

Compiled by

View browser:

It is also ok to try the above steps in index.css.

4. Page direct import: use the IMG tag

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <div id="title">webpack5 knowledge </div> <hr> <div class="box box1"></div> <hr> <div class="box box2"></div> <hr> <div class="box box3"></div> <hr> <img src="./src/assets/images/vite.png" class="img" /> </body> </html>Copy the code

In compiling webpack

The compilation passed.

Check the browser again:

The picture was not found.

5. Introduce images in JS

./src/index.js

const logo = require('./assets/images/vite.png');
​
const img = new Image();
img.src = logo;
document.body.appendChild(img);
Copy the code

Compile Webpack at run time

In fact, in the webpack4.x version of the introduction of the background mode, the compilation also reported an error.

If we have seen other webapck knowledge might tell us to install loader, come on, let’s see ~

Solve a problem:

Because using url-loader relies on file-loader, you need to install two

npm i url-loader file-loader -D
Copy the code

Modify configuration webpack.config.js

Test: /.(jpe? g|png|gif|svg)$/, loader: 'url-loader', }Copy the code

Run webpack

We can see that the compilation passed.

Viewing a browser

Gee, the pictures are not displayed.

What’s going on here? Good pit 🕳

Because: In Webpackage 5 we used assets-module because url-loader was deprecated in V5: Asset Module type can be used directly instead of raw-loader, url-loader, and file-loader.

Solve a problem:

We modify the configuration file webpack.config.js again to:

Test: /.(jpe? g|png|gif|svg)$/, type: "asset/resource", }Copy the code

Run webpack

We can see that the compilation passed.

Viewing a browser

We can see that the images introduced in the page HTML, other JS, CSS background images are displayed successfully.

Page HTML import image, this image is not displayed, how do we deal with?

Solve a problem:

At this point, a Loader configuration needs to be added again. Deal with HTML.

Modify configuration webpack.config.js

{/ picture/processing / / questions: can't deal with the default HTML img image test: /. (JPG | PNG | | GIF SVG) $/, / / loader: 'url - loader, type: "Asset /resource"}, {// handle HTML // error: cannot handle img image in HTML /.html$/, // To use a loader attribute value as a string, use a use value as an array // to use an HTML image in the img image (in charge of importing img in url-loader) loader: 'html-loader'}Copy the code

Run webpack

We can see that the compilation passed.

Viewing a browser

All images will now load normally!!

7. To solve a problem:

Possible lower versions of webpack5 are still not available at this time because: By default, html-loader is compiled in esModule mode, while url-loader processes images in commonJS mode. Therefore, you need to modify the options configuration of htmL-loader to set the esModule to false.

{
                test: /.html$/,
                loader: 'html-loader',
                options: {
                    esModule: false
                }
            }
Copy the code

I don’t need this webpack version anymore.

— — — — — — — —

Ok, let’s take a look at the image in the build folder,

The names of the image files have been changed and hash values have been added.

Requirement: How do I change the name of the packaged image hash?

Solve a problem:

Modify configuration webpack.config.js

Test: /.(jpe? g|png|gif|svg)$/, // loader: 'url-loader', type: "asset/resource", generator: {/ / and the output. AssetModuleFilename is the same, the time of this writing is introduced into will also add the filename path: '[name] [ext]},},Copy the code

[ext] indicates the extension

[name] : indicates the name of the file

Run webpack

We can see that the compilation passed.

Check your browser, no problem.

Look at the name of the image in the build file. It’s already the same name as before.

Requirement: If you want to use url-loader and other old loader can be used?

Solve a problem:

Sure, you can add type: ‘javascript/auto’,

Modify the configuration:

Test: /.(jpe? g|png|gif|svg)$/, // loader: 'url-loader', use: [{ loader: 'url-loader', options: [Object Module] because url-loader uses es6 Module by default, htMl-loader uses commonJS for images // Url-loader es6 module, use commonJS to parse esModule: false, // image rename // [hash:10] take the first 10 bits of the image hash // [ext] image original extension name: '[hash:10].[ext]'}}], // !!!!!! Assets loader (e.g. Raw-loader, url-loader, file-loader) is deprecated, you need to add this configuration type: 'javascript/auto', // type: "Asset/resource / / generator: {/ / / / and output assetModuleFilename is the same, the time of this writing is introduced into good will also add the path / / filename: '[name][ext]' // }, },Copy the code

Note: esModule: false. The default is true, using ES6 modularity; Set to false to use commonJs module syntax

Conclusion:

Webpack does not recognize the image file and needs to deal with it at packaging time.

note Note 2
webpack4 url-loader Note that url-loader relies on file-loader, so we need to install url-loader and file-loader at the same time. —-
webpack5 assets-module Asset /inline exports the data URI of a resource. Previously it was implemented using url-loader; Asset /source Exports the source code for the resource. Previously implemented by using raw-loader; Asset automatically selects between exporting a data URI and sending a separate file. Previously, the urL-loader was used and the resource volume limit was configured. To use url-loader, add type: ‘javascript/auto’,

For image processing, use the required loader as follows:

  • File-loader: resolves the problem of image import path and copies the image to a specified directory (dist by default)
  • Url-loader: decompresses file-loader. If the value of an image is smaller than the limit value, the image is converted to Base64 encoding. If the value is larger than the limit value, the image is copied using file-loader
  • Img-loader: compresses images

Other loaders that may be used to process images

Url – loader reference: www.webpackjs.com/loaders/url… www.npmjs.com/package/url…

File – loader reference: www.webpackjs.com/loaders/fil… www.npmjs.com/package/fil…

Img – loader reference: www.npmjs.com/package/img…

Imagemin – mozjpeg configuration items reference: www.npmjs.com/package/ima…

Imagemin – gifsicle configuration items reference: www.npmjs.com/package/ima…

Imagemin – pngquant configuration items reference: www.npmjs.com/package/ima…

Ps: of course, wepack5 is no longer neededRaw-loader, url-loader, and file-loader are used

Other Resource Configuration

  • A resource module is a module type that allows you to use resource files (fonts, ICONS, etc.) without having to configure an additional loader
  • raw-loader= >asset/sourceExport the source code of the resource
  • file-loader= >asset/resourceSend a separate file and export the URL
  • url-loader= >asset/inlineExport the data URI of a resource
  • Asset automatically selects between exporting a data URI and sending a separate file. Previously by usingurl-loaderAnd configure the resource volume limitation implementation
  • Rule.type
  • asset-modules

1. For example, font resource configuration

When we do front-end development, we will inevitably use font resources, sometimes the UI design, sometimes we download from some UI library, in which case how to configure, how to do? Let’s take a look at the actual combat

We can download some ICONS first, for example, we can use the official iconfont website

I this is to find their own font resources download;

  • Modify index.js to add SRC/ICONS /iconfont. CSS.
// ./src/index/js import dataJson from './data.json'; import './index.css'; import './index.less'; import './index.scss'; import './assets/icons/iconfont.css'; Function add(x, y) {return x + y; } console.log(add(1, 2)); console.log(dataJson, 'dataJson'); // js const logo = require('./assets/ vite.png'); const img = new Image(); img.src = logo; document.body.appendChild(img);Copy the code
  • Using styles

./index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <div id="title">webpack5 knowledge </div> <hr> <div class="box box1"></div> <hr> <div class="box box2"></div> <hr> <div class="box box3"></div> <hr> <img src="./src/assets/images/vite.png" class="img" /> <hr> <i class="iconfont icon-shouji"></i> <hr> </body> </html>Copy the code

Run Webpack and compile

Browser view

But if you’re loading the resource, after configuring the Loader and putting the font file in the right place, you can mix it up with an @font-face declaration. The local url (…). The directive is picked up and processed by Webpack just as it would be processed by an image:

Add to the style:

@font-face {
font-family: 'MyFont';
src: url('./src/assets/icons/iconfont.ttf') format('ttf'),
font-weight: 600;
font-style: normal;
}
​
.hello {
  color: red;
font-family: 'MyFont';
}
Copy the code

}}}}}}}}}}}}}}}}}}}}

{
                    test: /.(woff|woff2|eot|ttf|otf)$/i,
                    type: 'asset/resource',
                },
Copy the code

2. CSV, TSV and XML files

To import CSV, TSV, and XML, you can use cSV-loader and XML-loader. Let’s deal with loading these three types of files:

Install dependencies

npm install --save-dev csv-loader xml-loader
Copy the code

./src/data.xml

<? The XML version = "1.0" encoding = "utf-8"? > <note> <to>Mary</to> <from>John</from> <heading>Reminder</heading> <body>Call Cindy on Tuesday</body> </note>Copy the code

./src/data.csv

to,from,heading,body Mary,John,Reminder,Call Cindy on Tuesday Zoe,Bill,Reminder,Buy orange juice Autumn,Lindsey,Letter,I  miss youCopy the code

./src/index.js

import Data from './data.xml';
import Notes from './data.csv';
console.log(Data);
console.log(Notes);
Copy the code

Modified in the webpack.config.js configuration file

{
        test: /.(csv|tsv)$/i,
        use: ['csv-loader'],
      },
      {
        test: /.xml$/i,
        use: ['xml-loader'],
      },
Copy the code

Run the Wepack build and check it out!

Working Mode Configuration

mode

Mode: Instructs Webpack to use the configuration of the corresponding Mode.

options describe The characteristics of
development The value of process.env.node_env in DefinePlugin is set to development. Enable NamedChunksPlugin and NamedModulesPlugin. An environment in which code debugging can run locally
production The value of process.env.node_env in DefinePlugin is set to production. Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and TerserPlugin. An environment that optimizes code to run online
none Do not use any default optimization options Webpack has supported 0 configuration packaging since 4,

Working Mode Configuration

mode

Mode: Instructs Webpack to use the configuration of the corresponding Mode.

options describe The characteristics of
development The value of process.env.node_env in DefinePlugin is set to development. Enable NamedChunksPlugin and NamedModulesPlugin. An environment in which code debugging can run locally
production The value of process.env.node_env in DefinePlugin is set to production. Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and TerserPlugin. An environment that optimizes code to run online
none Do not use any default optimization options Webpack has supported 0 configuration packaging since 4,

Working Mode Configuration

  1. Simply provide the mode option in the configuration object: webpack.config.js

    Module. exports = {mode: 'development',// mode: 'production', // mode: 'production'};Copy the code

To distinguish the environment

In real practice, we need to distinguish between different environments, local development and deployment online, different environments have different requirements for the whole project; Specific can be divided into the following situation:

The development environment

  • Focus on package build speed

  • Focus on code debugging

The production environment

  • Focus on package build speed

  • Focus on code performance:

  • Need to compress image volume

  • A smaller package size is required

  • Etc.

To distinguish the environment

  • --modeUsed to set the values in the moduleprocess.env.NODE_ENV
  • --envFunction parameters used to set the WebPack configuration file
  • cross-envUsed to set the Node environmentprocess.env.NODE_ENV
  • DefinePluginUsed to set global variables in a module
Command line configuration –mode
  • The default mode for Webpack isproduction
  • webpack serveThe default mode isdevelopment
  • It can be passed in modulesprocess.env.NODE_ENVGets the current environment variable, which cannot be obtained in the WebPack configuration file
 "scripts": {
    "build": "webpack",
    "start": "webpack serve"
  },
Copy the code

index.js

console.log(process.env.NODE_ENV); // development | productionCopy the code

webpack.config.js

console.log('NODE_ENV',process.env.NODE_ENV); // undefinedCopy the code

NODE_ENV in ps: index.js is different from process.env.node_env in webpack.config.js.

package.json

"build": "webpack --mode=production",  "start": "webpack --mode=development serve"
Copy the code

index.js

console.log(process.env.NODE_ENV); // development | productionCopy the code

webpack.config.js

console.log('NODE_ENV',process.env.NODE_ENV); // undefinedCopy the code
Command line configuration –env

package.json

"scripts": {   "dev": "webpack serve --env=development",   "build": "webpack --env=production",}
Copy the code

index.js

console.log(process.env.NODE_ENV); // undefinedCopy the code

webpack.config.js

console.log('NODE_ENV',process.env.NODE_ENV); // undefinedCopy the code

webpack.config.js

There is one change that must be made to our Webpack configuration. Module.exports normally points to configuration objects. To use the env variable, you must convert module.exports to a function:

module.exports = (env,argv) => { console.log('env',env); // development | production};Copy the code
Define the environment variable DefinePlugin

Use the WebPack built-in plug-in DefinePlugin to set global variables within a module.

Note:

  • Set global variables (nowindow), all modules can read the value of this variable
  • Can pass in any moduleprocess.env.NODE_ENVGets the current environment variable
  • But not inThe node environmentGets the current environment variable from the webPack configuration file

Each key in DefinePlugin is an identifier.

  • ifvalueIt’s a string. It’s going to be treated ascodefragment
  • ifvalueIt’s not a string, it’s gonna bestringify
  • ifvalueIs an object, the normal object definition
  • ifkeyThere aretypeofIt only applies totypeofCalls to define
//webpack.config.js const webpack = require('webpack'); module.exports = { plugins: [new webpack.defineplugin ({// Define a key that is used only at compile time instead of a value. 'process.env.node_env' has only real 'development' or other set json.stringify (process.env.node_env) values 'process.env.node_env ': json.stringify (process.env.node_env), DEV: json.stringify (' DEV '), // string FLAG: 'true' //FLAG is a Boolean})]}Copy the code

index.js

console.log(process.env.NODE_ENV); // productionCopy the code

webpack.config.js

console.log('process.env.NODE_ENV',process.env.NODE_ENV); // undefined console.log('NODE_ENV',NODE_ENV); // error!!Copy the code
usecross-env****

For different needs, the first thing to do is to do a good job of environmental differentiation

  • Can only be setThe node environmentNODE_ENV

1. Install cross-env

npm install cross-env -D
Copy the code

2. Configure the startup command

Change the package. The json

"scripts": {
  "dev": "cross-env NODE_ENV=dev webpack serve --mode development",
  "test": "cross-env NODE_ENV=test webpack --mode production",
  "build": "cross-env NODE_ENV=prod webpack --mode production"
}
Copy the code

3. Modify the configuration file

const { resolve } = require('path'); const { CleanWebpackPlugin } = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') Const config = (mode) => {return {// webpack configuration // entry entry: './ SRC /index.js', // output output: {// output path __dirname nodejs variable represents the absolute directory path of the current file path: resolve(__dirname, 'build'), // output Ming filename: 'built.js'}, // loader configuration module: {rules: [{// Matches the file test that ends with CSS: /.css$/, // use css-loader to make webpack recognize // single loader using loader attributes //loader: 'css-loader' // Multiple loaders need to use the use attribute in reverse order, i.e. the end of the array -> the beginning of the array use: ['style-loader', 'css-loader']}, {// Match files ending in. Less: /.less$/, / / less - loader speak less file into the CSS file (need to download the two rely on less and less - loder) / / CSS - loader in the CSS file into a commonjs module is loaded into the js / / style is the inside content strings // use array to execute in backorder, that is, execute 'style-loader' first, 'style-loader' use: ['style-loader', 'css-loader', 'less-loader']}, {// Match files ending in. SCSS test: /. SCSS $/, use: ['style-loader', 'css-loader', 'sass-loader']}, {// /.(jpe?g|png|gif|svg)$/, // loader: 'url-loader', use: [{ loader: 'url-loader', options: { // publicPath: './img', // relative to the image location of the packed index.html // output to the img directory in build // outputPath: 'img/', // if the image size is less than 8KB, it will be processed base64 (usually 8-12KB is suitable for project) // Advantages: reduce the number of requests (reduce server stress) // disadvantages: larger image size (slower file request) // limit: [Object Module] because url-loader uses es6 Module by default, htMl-loader uses commonJS for images // Url-loader es6 module, use commonJS to parse esModule: false, // image rename // [hash:10] take the first 10 bits of the image hash // [ext] image original extension name: '[hash:10].[ext]'}}], // !!!!!! Assets loader (e.g. Raw-loader, url-loader, file-loader) is deprecated, you need to add this configuration type: 'javascript/auto', // type: "Asset/resource / / generator: {/ / / / and output assetModuleFilename is the same, the time of this writing is introduced into good will also add the path / / filename: '[name][ext]' //},}, {// /.html$/, // To use a loader attribute value as a string, multiple use values as an array // to use the HTML img image (responsible for importing img in the url-loader process) loader: 'html-loader', // htmL-loader can't display images. Turn off es6 module parsing. Use commonJS module parsing. False //}}]}, // plugins: [// function: New HtmlWebpackPlugin({// Copy './index.html') {// Copy './index.html' Template: './index.html'}), // clear the build folder new CleanWebpackPlugin()], mode, // development mode // mode: 'production', // production mode // devServer for automation (auto compile auto open browser auto refresh browser...) NPX webpack-dev-server = NPX webpack-dev-server = NPX webpack-dev-server DevServer: {// NPX webpack-dev-server: {// NPX webpack-dev-server: {// NPX webpack-dev-server: Resolve (__dirname, 'build'), // enable gzip compress: true, // port: 8888, // automatically open browser: true, // enable HMR function hot: Proxy: {'/ API ': {target: 'http://localhost:5000', pathRewrite: {'/ API ': {target: 'http://localhost:5000', pathRewrite: { '^/api': '' } } } }, } } module.exports = (env, argv) => { console.log('argv.mode=', argv.mode, "env:", Return config(argv.mode); }Copy the code

4. Run the command

  • performnpm run build
  • performnpm run dev

DevServer configuration

Development server DevServer for automation (auto compile, auto open browser, auto refresh browser…)

Features: The conductor compiles the package in memory without any output

2, start devServer with NPX webpack-dev-server

1. Download dependencies

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

2, use, modify the webpack.config.js file

const { resolve } = require('path'); const { CleanWebpackPlugin } = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') Module.exports = {// webpack configuration // entry: './ SRC /index.js', // output: {// output path __dirname nodejs variable represents the absolute directory path of the current file path: resolve(__dirname, 'build'), // output Ming filename: 'built.js', clean: True}, // loader configuration module: {rules: [{// Matches the CSS file test: /.css$/, // use css-loader to make webpack recognize // single loader using loader attributes //loader: 'css-loader' // Multiple loaders need to use the use attribute in reverse order, i.e. the end of the array -> the beginning of the array use: ['style-loader', 'css-loader']}, {// Match files ending in. Less: /.less$/, / / less - loader speak less file into the CSS file (need to download the two rely on less and less - loder) / / CSS - loader in the CSS file into a commonjs module is loaded into the js / / style is the inside content strings // use array to execute in backorder, that is, execute 'style-loader' first, 'style-loader' use: ['style-loader', 'css-loader', 'less-loader']}, {// Match files ending in. SCSS test: /. SCSS $/, use: ['style-loader', 'css-loader', 'sass-loader']}, {// /. (jpe? G | PNG | | GIF SVG) $/, type: "asset", the generator: {/ / and the output. AssetModuleFilename is the same, the time of this writing is introduced into will also add the filename path: 'imgs / [name] [6] hash: [ext]', / / packaging for resources after the introduction of the file name already have/img / / publicPath: '/'},}, {test: /. (woff | woff2 | eot | the vera.ttf | otf) $/ I type: 'asset/resource'}, {dealing with HTML / / / / : the default processing, the HTML img image test: /.html$/, // To use a loader attribute value as a string, multiple use values as an array // to use the HTML img image (responsible for importing img in the url-loader process) loader: 'html-loader', // htmL-loader can't display images. Turn off es6 module parsing. Use commonJS module parsing. False //}}]}, // plugins: [// function: New HtmlWebpackPlugin({// Copy './index.html') {// Copy './index.html' Template: './index.html'})], mode: 'development', // development mode // mode: 'production', // production mode // devServer for automation (auto compile auto open browser auto refresh browser...) NPX webpack-dev-server = NPX webpack-dev-server = NPX webpack-dev-server  devServer: {// NPX webpack-dev-server error: contentBase static; // NPX webpack-dev-server error: contentBase static; // NPX webpack-dev-server error: contentBase static; Static: resolve(__dirname, 'build'), // gzip compress: true, // port: 8888, // automatically open browser: Hot: true, // domain host: 'localhost', // server proxy: {'/ API ': {target: 'http://localhost:5000', pathRewrite: { '^/api': '' } } } }, }Copy the code

For our convenience later, modify package.json and add the startup command

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

You can also run NPX webpack-dev-server directly from the command line

NPX webpack-dev-server will automatically open the browser, the port number has also been changed ~ and will listen to our file changes ~

Pit comes need to pay attention to:

⚠ ️ note: The webpack-dev-server version used in this article is ^4.7.4. If version >= 4.0.0, use devserver. static. Versions smaller than 4.0.0 use the devServer.contentbase configuration item.

Write WebPack Serve in package.json in WebPack5

  • Webpack-dev-server is not written to any output files after compilation. Instead, you keep the bundle files in memory and then serve them to the server as if they were real files mounted on the server root path. If your page wants to find bundle files in a different path, you can modify this by using the devMiddleware. PublicPath option in the Dev Server configuration.
  • You can access it through http://[devserver.host]:[devserver. port]/[output.publicpath]/[output.filename]
  • Error: contentBase changed to static or commented out /webpack5 does not need to configure contentBase
  • Where to find files

What is the difference between Loader and Plugin?

  • Loader literal translation forloader. Webpack treats all files as modules, but Webpack natively only parses JS files, and if you want to package other files, you use loader. So what Loader does is give WebPack the ability to load and parse non-javascript files
  • The Plugin toThe plug-in. Plugin can extend the functionality of WebPack to make it more flexible. A number of events are broadcast during the life cycle of a Webpack run, and the Plugin can listen for these events and change the output when appropriate through the API provided by Webpack

What is the webPack build process?

  • Initialization parameters: read and merge parameters from configuration files and Shell statements to get the final parameters;

  • Start compiling: initialize the Compiler object using the parameters obtained in the previous step, load all the configured plug-ins, and execute the object’s run method to start compiling. Identify entry: Locate all entry files according to the entry in the configuration

  • Compiling module: starting from the entry file, call all configured Loader to compile the module, find out the module that the module depends on, and then recurse this step until all the entry dependent files have gone through this step;

  • Complete module compilation: After using Loader to translate all modules in Step 4, the final translated content of each module and the output resources of their dependencies are obtained: According to the dependency relationship between the entry and modules, the Chunk is assembled one by one containing multiple modules, and then each Chunk is converted into a separate file and added to the output list. This step is the last chance to modify the output content

  • Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the file content to the file system

    In the above process, Webpack will broadcast a specific event at a specific point in time, the plug-in will execute a specific logic after listening for the event of interest, and the plug-in can call the API provided by Webpack to change the running result of Webpack

Thank you

This is the end of this introduction, then will be sorted out webpack knowledge system content sharing, enjoy looking forward to, thank you for reading ~~