Webpack has been updated to 5.37.0. The biggest change is the update from WebPack-3 to Webpack-4. Webpack-4 implemented a word: 0 configuration startup. This article uses WebPack4 to study, WebPack4 after learning, Webpack5 is not easy, this article is from the beginning of the foundation of 0 teaching, what is the problem, you can give me a message.

Read this article to learn:

  • The basic use of WebPack
  • Use plug-ins in WebPack
  • Use loader in WebPack
  • Knowledge of PostCSS and compatibility with any browser

First, early preparation

1.1 Environment Construction

Step 1: Create a folder and add the SRC directory

Step 2: in the index.js file

console.log("Hello World!!!" )Copy the code

Step 3:.npmrc file

  • Set NPM source to Taobao. This is the default NPM configuration file. You can also set it globally.
registry = https://registry.npm.taobao.org/
Copy the code

Step 4: Initialize the package.json file

npm init -y
Copy the code

Step 5: Install the NPM package

  • After webPack4, you must install Webpack-CLI to run the package. These versions are recommended.
npm install webpack@4.43. 0 webpack-cli@3.312. -D
Copy the code

Step 6: In the package.json file, configure the start command

{
    "script": {"build":"webpack"}}Copy the code

2. Understanding of relevant concepts

Chunk: code snippets, which are generated when a module is packaged and compiled by WebPack

Chunks: indicates the chunk group

Bundle: The output of webPack after compilation, that is, all files under the dist directory are called bundles

Module: NodeJS Everything is a module. Each file is a module

Loader: WebPack supports only. Js and. Json files by default. You need to install the specified Loader to compile and package other types of files. (Multiple Loaders are executed from back to front)

Plugin: Extends webPack’s functionality

A bundle that consists of at least one chunk (or at least one module or modules)

It doesn’t matter if you don’t understand the concept. Follow the passage and you will understand it naturally.

Iii. Practical operation of the project

This is the default webPack configuration file. When you run WebPack, you will read the configuration from this file.

3.1 Basic Usage

Zero configuration using WebPack

After WebPack4 came out, has been the implementation of a sentence is zero configuration start, let’s see exactly how zero configuration start?

The script command was configured when the project was set up. Now we run the NPM run build command directly. From the following picture, we can see that the dist directory is successfully packaged.

The zero configuration uses WebPack, equivalent to the following configuration:

// In the 'webpack.config.js' file
const path = require ('path');
module.exports = {
  entry: './src/index.js'.mode: 'development'.output: {
    path: path.resolve (__dirname, './dist'),
    filename: 'main.js',}};Copy the code

3.2 join the loader

By default, webPack only supports.js and.json files. If you want to process other files, you need to install the corresponding Loader.

Loaders are executed in the following order. Each Loader does only one thing

Scenario 1: Supports files ending in.css. Let’s see how to configure them.

Step 1: Install the dependencies

npm install css-loader style-loader -D
Copy the code

Step 2: Modify the webpack.config.js file

const path = require ('path');
module.exports = {
  entry: './src/index.js'.mode: 'development'.output: {
    path: path.resolve (__dirname, './dist'),
    filename: 'main.js',},module: {
    rules: [{test: /\.css$/,
        use: ['style-loader'.'css-loader'],},],},};Copy the code

Step 3: Create a new CSS /index.css file and introduce it in index.js

// CSS /index.css file
body{
    background-color: aqua;
}

// In the index.js file
import './css/index.css';
Copy the code

Step 4: Run the command package

npm run build
Copy the code

Step 5: In the generated dist directory, create a new index. HTML file and introduce the generated main.js

<! DOCTYPEhtml>
<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>
    <script src="./main.js"></script>
</body>
</html>
Copy the code

Step 5: Open the index.html file in the browser, and the style is set successfully.

Scenario 2: Support for. SCSS syntax

Step 1: Install the dependencies

npm install sass-loader@9.0. 0 sass -D
Copy the code

Why install Sass-Loader version 9.0.0? If the version is not specified, the latest version of Sass-Loader is installed by default. The latest version only supports WebPack5

Step 2: Create a.scss file and import it in the index.js file

Step 3: Modify the webpack.config.js file

const path = require ('path');
module.exports = {
  entry: './src/index.js'.mode: 'development'.output: {
    path: path.resolve (__dirname, './dist'),
    filename: 'main.js',},module: {
    rules: [{test: /\.css$/,
        use: ['style-loader'.'css-loader'],},],},};Copy the code

Step 4: Run the command package

npm run build
Copy the code

Step 5: In the generated dist directory, create a new index. HTML file and introduce the generated main.js

<! DOCTYPEhtml>
<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 style="height:40px"></div>
    <script src="./main.js"></script>
</body>
</html>
Copy the code

Step 5: Open the index.html file in the browser, and the style is set successfully.

Scenario 3: Use the PostCSS to achieve compatibility with any browser

As for the front end, if someone asks you to be compatible with IE8, then you are not the impulse to kill him. Don’t worry, today we’ll take a look at how to use WebPack CSS to work with any version of the browser.

With.scSS and.css files already supported, let’s go to the browser and see what our CSS is compiled into. As you can see from the figure below, it is just a normal compilation in the browser, without any compatibility.

This section describes the PostCSS

Attach the Chinese document of PostCSS first

Postcss is a tool for compiling CSS. It is similar to Babel for javascript. The common functions are as follows:

  1. Use the next generation CSS syntax
  2. Auto-complete the browser prefix
  3. Automatically converts px into REM
  4. CSS code compression and so on

Postcss is just a tool. It doesn’t do anything to THE CSS itself.

Browser compatibility is achieved through the plug-in AutopreFixer in PostCSS.

Postcss configuration in the project

Step 1: Install the dependencies

npm install postcss postcss-loader autoprefixer -D
Copy the code

Step 2: Modify the webpack.config.js file

const path = require ('path');
module.exports = {
  entry: './src/index.js',
  mode: 'development',
  output: {
    path: path.resolve (__dirname, './dist'),
    filename: 'main.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
      },
    ],
  },
};
Copy the code

Step 3: Create a postcss.config.js file at the project root (this is the default configuration file for postCSS)

module.exports = {
  plugins: [
    require ('autoprefixer') ({
      overrideBrowserslist: ['last 2 versions', '> 1%'],
    }),
  ],
};
Copy the code

Step 4: Modify the index. SCSS file, we use display:flex to test

Step 5: Run the NPM run build command to package

Step 6: In the generated dist directory, create a new index. HTML file and introduce the generated main.js

<! DOCTYPEhtml>
<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>
    <script src="./main.js"></script>
</body>
</html>
Copy the code

Step 7: Take a look at the results of the compilation in the browser. As you can see in the figure below, PostCSS is compatible with Display: Flex

Intellectual developmentbrowserslist

First of all, browserslist is basically a collection of target browsers, so if you use the plug-in Autoprefixer, you have to tell it, you have to tell it which browsers you want to be compatible with, and officially you have to configure the collection of browsers for it. As I said above, require(“autoprefixer”) followed by configuration is one way to configure the PostCSS plug-in

The configuration of Browserslist can be directly and rudely configured after autoprefixer as I did, either in a package.json file or in a.browserslistrc configuration file. All of the tools that use Browserslist are going to actively look up the configuration of Browserslist

A brief introduction to the collection of browsers used in the project:

  • Last 2 versions: The last two major versions of the browser
  • > 1% : Browsers with a market share greater than 1%

Description of common collection ranges
The scope of instructions
last 2 versions If IOS 12 is the latest version, then the two backward compatible versions would be IOS 11 and IOS 12
> 1% Over 1% of the world’s population uses a browser, similar> 5% in USMore than 5% of users in the United States
Cover 99.5% Coverage of 99.5% of major browsers
chrome > 50,ie 6-8 Specify a browser version range
unreleased``versions Note The browser beta version is available
not ie < 11 The following versions are not compatible with IE11
since 2013,last 2 years All browser versions released in a time range
maintained,node versions All versions of Node maintained by the Node Foundation
current node The node version of the current environment
dead Browsers that pass the Last 2 Versions filter have less than 0.5% global usage and are officially not under maintenance or have not been updated in fact for two years
defaults By default, > 0.5%. Last 2 Versions Firefox ESR Not Dead
Run a command to view the browser selected in the collection
npx browserslist "last 2 versions,>%1"
Copy the code

3.3 Adding a Plug-in

Context of use of plug-ins: The use of plug-ins in WebPack, is to expand webPack functions.

Scenario 1: Delete the dist directory every time you build

For example, we usually use vue-CLI to create a project. Every time we package, the dist directory will be deleted first, and then build again. So how do we implement this function?

  1. Install dependencies
npm install clean-webpack-plugin -D
Copy the code
  1. Modify thewebpack.config.jsfile
const path = require ('path');
const {CleanWebpackPlugin} = require ('clean-webpack-plugin');
module.exports = {
  entry: './src/index.js'.mode: 'development'.output: {
    path: path.resolve (__dirname, './dist'),
    filename: 'main.js',},module: {
    rules: [{test: /\.css$/,
        use: ['style-loader'.'css-loader'],},],},plugins: [new CleanWebpackPlugin ()],
};
Copy the code

3. The dist directory is deleted every time the NPM run build is executed. This is how plugins are used and configured in WebPack.

Scenario 2: Each build, create a new index. HTML file

Each time we generated the dist directory, we had to manually create a new index. HTML and manually import the generated JS file, which would be very troublesome. Let’s take a look at how plugins can help us do this.

Step 1: Install the dependencies

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

Step 2: Configuration in the project Is configured in the webpack.config.js file

const path = require ('path');
const htmlwebpackplugin = require ('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  mode: 'development',
  output: {
    path: path.resolve (__dirname, './dist'),
    filename: 'main.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
      },
    ],
  },
  plugins: [new htmlwebpackplugin ()],
};
Copy the code

Step 3: Each time we run the NPM run build command, we generate an index. HTML file in the dist directory

html-webpack-pluginSupporting configuration Templates

After the html-webpack-plugin is configured for the template, it is generated from our template HTML file.

Create a new SRC /index.html file,

<! DOCTYPEhtml>
<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>Hello World</div>
</body>

</html>
Copy the code

Modify the webpack.config.js file

const path = require ('path');
const htmlwebpackplugin = require ('html-webpack-plugin');

module.exports = {
  ...
  plugins: [
    new htmlwebpackplugin ({
      template: './src/index.html',
    }),
  ],
};
Copy the code

Scenario 3: Pull out the CSS file

If we want to put the CSS files in a separate CSS directory so that the directory structure is clear, how do we do this?

We used the mini-CSs-extract-plugInc package to fulfill our requirements

Step 1: Install the dependencies

npm install mini-css-extract-plugin -D
Copy the code

Step 2: Modify the webpack.config.js file

const path = require ('path');
const htmlwebpackplugin = require ('html-webpack-plugin');
const {CleanWebpackPlugin} = require ('clean-webpack-plugin');
const minicssextractplugin = require ('mini-css-extract-plugin');
module.exports = {
  ...
  module: {
    rules: [{...test: /\.scss$/,
        use: [
          'style-loader',
          minicssextractplugin.loader,
          'css-loader'.'postcss-loader'.'sass-loader',],},],},plugins: [...new minicssextractplugin ({
      filename: 'css/[name].css',})]};Copy the code

Step 3: Run the NPM run build command to pull out the CSS file successfully