Webpack5 quick start, ship new version, suggested collection

This document is shared by Huawei cloud community webPack5 Quick Start, New ship version, Recommended collection, author: Northern Lights Night.

1. Get started quickly

1.1 Webpack Functions:

Packaging: Different types of resources are packaged according to module processing. Static: The final output of static resources after packaging. Modules: WebPack supports modular development of different specifications

1.2 Installing the WebPack:

Terminal input: NPM install webpack -g

1.3 Fast simulation to build a project directory:

Utiles. Js:

function add(a,b){
    console.log(a+b);
}
export {add} ;
Copy the code

Index. Js:

Import {add} from './utiles/ uties.js' add(6,9);Copy the code

1.4 WebPack Packaging:

Terminal input: webpack Webpack will automatically find the SRC directory, and then find the index.js entry file, and then package, and finally generate a dist directory as the packaged content.

Index.html introduction:

<script src=".. /dist/main.js"></script>Copy the code

Results:

Ii. Basic Use:

2.1. Configuration File:

You can define the configuration in the configuration file, how you want to package, you can set a lot of conditions. Webpack is packaged according to the configuration rules of your configuration file. Create a new webpack.config.js file in the SRC directory and write the configuration information. Such as the most basic entrance and exit:

const path = require('path'); Module.exports = {// export file path entry: './ SRC /index.js', //path export file path, filename filename output: {path: path.resolve(__dirname, 'dist'), filename: 'build.js', }, };Copy the code

The terminal successfully packaged the build.js file after typing webpack, just like the main.

2.2. Loader:

Why use Loader: WebPack can only understand JavaScript and JSON files, which is available out of the box with WebPack. Loader enables WebPack to process other types of files (CSS type files, image type, TXT type, etc.) and convert them into valid modules for use.

2.2.1 CSS – loader:

For example, if I want webPack to pack CSS, terminal type the following command to install CSS-loader first:

npm i css-loader -D
Copy the code

1. You can specify loader when importing CSS files, so that no error is reported. Add CSS-loader before importing CSS files. :

import 'css-loader! ./css/index.css'Copy the code

2. Of course, you can also set in the configuration file:

const path = require('path'); Module.exports = {//path file path entry: './ SRC /index.js', //path file path, filename filename output: {path: Path. resolve(__dirname, 'dist'), filename: 'build.js',}, // Define some rules for each element in the array. / \. CSS $/, use: [{loader: 'CSS - loader'}] / / shorthand for use: [' CSS - loader]}}};Copy the code

The test property defines a regular expression that matches the type of file to be processed. Identify which files will be converted. The use attribute defines which loader should be used during conversion. After the configuration file is configured, don’t forget to import the CSS file in the index entry file.

2.2.2 style – loader:

The CSS -loader can only recognize THE CSS file, and the CSS style can be displayed on the page after the introduction of style-loader.

Installation:

npm i style-loader -D
Copy the code

Config file rules:

Because Webpack executes from back to front, style-loader is written before CSS-loader.

[{test: /\.css$/, use: ['style-loader','css-loader']}]}Copy the code

2.2.3 sass – loader:

For example, I think Webpack can package SCSS file types. Can not sass can read this article sass full analysis.

Install the sass:

npm i sass -D
Copy the code

Convert SCSS to CSS (note the SCSS sibling path, also terminal input) :

sass index.scss:ouput.css
Copy the code

In the entry file index.js import:

import './css/ouput.css'
Copy the code

Install the sass – loader:

npm i sass-loader -D
Copy the code

Configuration rules:

Rules :[{test: /\. CSS $/, use: ['style-loader','css-loader']}, {test: /\.scss$/, use: ['style-loader','css-loader'] } ] }Copy the code

Packaging:

webpack
Copy the code

2.3 browserslist:

Webpack supports all ES5-compliant browsers (IE8 and below are not supported). If you want to support older browsers, there are tools you need to use. Browserslist is installed by default when you install WebPack, and it knows the usage data for each browser and configures it.

The site also provides current browser usage data. More on that later.

2.4 PostCSS-loader handling CSS compatibility:

Postcss is a JavaScript style conversion tool that handles CSS compatibility issues. This is the tool that adds compatible prefixes to the CSS code we write.

First, you can use this site to learn what prefixes CSS adds and how it works with major browsers.

Installation:

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

Configuration file:

Add postCSs-loader to the CSS file type and set the following parameters:

{ test: /\.css$/, use: ['style-loader', 'css-loader', // add postcss-loader; Plugins :[require('autoprefixer')]}}}]}, plugins:[require('autoprefixer')]}Copy the code

Create a new file named.browserslistrc under index.js and write the compatibility conditions, such as:

> 0.1%
last 2 version
not dead
Copy the code

Then the CSS code will automatically add compatible code after the terminal enters webpack.

If more compatibility is needed, postCSS-preset -env is installed:

npm i  postcss-preset-env -D
Copy the code

Add configuration (to complete) :

const path = require('path'); Module.exports = {//path file path entry: './ SRC /index.js', //path file path, filename filename output: {path: Path. resolve(__dirname, 'dist'), filename: 'build.js',}, // Define some rules for each element in the array. /\.css$/, use: ['style-loader', 'css-loader', // add postcss-loader; Plugins :[require('autoprefixer'), plugins:[require('autoprefixer'), require('postcss-preset-env') ] } } } ] }, { test: /\.scss$/, use: ['style-loader','css-loader'] } ] } };Copy the code

Only postCSS-preset -env can be retained.

{ test: /\.css$/, use: ['style-loader', 'css-loader', // add postcss-loader; Plugins :[' postCSs-env ']}}}]},Copy the code

Postcss.config. js: postcss.config.js: postcss.config.js: postcss.config.js: postcss.config.js: postcss.config.js: postcss.config.js: postcss.config.js: postcss.config.js: postcss.config.js:

module.exports = {
    plugins: [
        require('postcss-preset-env')
    ]
}
Copy the code

Import postCSs-loader directly from webpack.config.js configuration file:

Use: ['style-loader', 'css-loader', // add postcss-loader' postcss-loader']Copy the code

2.5 importLoaders:

ImportLoaders: Configures the number of loaders for CSS-loaders before @import resources. If you set the value of importLoaders to several, the CSS file imported by @import will also execute the loader that is not executed before. As follows:

 use: [
                'style-loader',
                {
                   loader:'css-loader',
                   options:{
                       importLoaders:1
                   }
                },
                 'postcss-loader'
            ]
Copy the code

A CSS file will execute the previous 3 Loaders. If the CSS file has a CSS file imported by the import syntax, the imported CSS file will not execute the last postCSs-loader. But I want to execute, so configure importLoaders to indicate how many loaders the imported CSS file will also execute backwards. (Note that Webpack is executed from back to front)

2.6 File-loader Processing Images:

File – loader:

1. We can recognize images when we import them as a module. 2. You can copy binary resources to the specified directory. If you do not specify this directory, you will find the default dist directory.

Installation:

npm i file-loader -D 
Copy the code

2.6.1 Imported from SRC in JS:

You can create an IMG folder in the SRC directory to store your images.

Config file (add a new rule to the rules array) :

{ test: /\.(png|svg|gif|jpe? g)$/, use:['file-loader'] }Copy the code

1. First use: Add. Default at the end of an image when importing it as a module, for example:

var img = document.createElement('img'); img.src = require('.. /img/1.jpg').default; document.body.appendChild(img);Copy the code

2. Second usage: If you don’t want to add. Default at the end of the module import, add the esModule parameter to the configuration file:

{ test: /\.(png|svg|gif|jpe? g)$/, use:{ loader:'file-loader', options: { esModule:false } } }Copy the code

3. If you don’t want to write this, you can also use the es6 module import mode:

Preloading the image module:

import src from '.. /img/1.jpg';Copy the code

And then:

var img = document.createElement('img');
   img.src = src;
   document.body.appendChild(img);
Copy the code

Finally, the terminal webpack will be ok. Currently, the images will be packed into the dist directory by default.

2.6.2 Imported by URL in the CSS:

SRC = “CSS” SRC = “CSS” SRC = “CSS” SRC = “CSS”

{ test: /\.css$/, use: [ 'style-loader', { loader:'css-loader', options:{ importLoaders:1, esModule:false } }, 'postcss-loader' ] }, { test: /\.(png|svg|gif|jpe? g)$/, use: ['file-loader'] }Copy the code

Webpack will pack the image in the dist directory by default:

div { width: 200px; height: 200px; background-image: url(".. /img/1.jpg"); }Copy the code

Default position, such as (image name automatically based on content algorithm) :

Insert a picture description here

2.6.3 Setting the Output Position and Image Name:

We can set the place and name of the packaged picture.

Modify the image rule of the configuration file by adding a name configuration attribute and an OutputPath attribute (location) :

{ test: /\.(png|svg|gif|jpe? g)$/, use: { loader:'file-loader', options:{ name: '[name].[hash:6].[ext]', outputPath: 'img' } } }Copy the code

Where the name attribute indicates: [ext] extension, [name] file name, [hash] file content. Outputpath property: Specifies the img directory directly, which is placed in the dist directory by default.

Insert a picture description here

Two attributes can be combined to simply write:

{ test: /\.(png|svg|gif|jpe? g)$/, use: { loader:'file-loader', options:{ name: 'img/[name].[hash:6].[ext]', } } }Copy the code

2.7 UrL-loader image Processing:

Url-loader can convert an image into a Base64 string, which can load the image more quickly (it is suitable for a small number of image files, or file-loader is used if the image file is too large). File-loader is slower than copy.

Installation:

npm i url-loader -D
Copy the code

File-loader (); file loader ();

{ test: /\.(png|svg|gif|jpe? g)$/, use: { loader:'url-loader', options:{ name: 'img/[name].[hash:6].[ext]', } } }Copy the code

Unlike file-loader, the image is loaded into the code as a Base64 string after packaging, so it is no longer visible in the directory:

The key is that the url-loader contains file-loader. You can set a limit attribute. When the size of an image exceeds the limit, url-loader will call file-loader to execute the image.

Set a raft value to 20KB. If the raft value is smaller than 20KB, url-loader will be executed. If the raft value is larger than 20KB, file-loader will be executed

{ test: /\.(png|svg|gif|jpe? g)$/, use: { loader:'url-loader', options:{ name: 'img/[name].[hash:6].[ext]', limit: 20*1024 } } }Copy the code

2.8 Asset Processing image:

After Webpack5, you can directly use asset to process images without configuring file-loader or URl-loader. Can better simplify the use. And it’s a built-in webpack5 module, so you don’t have to install anything else.

Config file modify image rules:

1. By default, copy image to dist directory by default (same as file-loader without name and path) :

{ test: /\.(png|svg|gif|jpe? g)$/, type: 'asset/resource' }Copy the code

(dist) add assetModuleFilename to the output package exit path. (dist) Add assetModuleFilename:

Output: {path: path.resolve(__dirname, 'dist'), filename: 'build.js', assetModuleFilename:'img/[name].[hash:6][ext]' }, { test: /\.(png|svg|gif|jpe? g)$/, type: 'asset/resource' }Copy the code

Create a “generator” for filename to write to the filename and position of the filename.

{ test: /\.(png|svg|gif|jpe? g)$/, type: 'asset/resource', generator:{ filename:'img/[name].[hash:6][ext]' } }Copy the code

4. If you want to convert an image to a Base64 string instead of copying it, change the rules as follows:

{ test: /\.(png|svg|gif|jpe? g)$/, type: 'asset/inline', }Copy the code

MaxSize = 30kb; maxSize = 30kb; maxSize = 30kb;

{
            test: /\.(png|svg|gif|jpe?g)$/,
            type: 'asset',
            generator:{
                filename:'img/[name].[hash:6][ext]'
            },
            parser:{
                dataUrlCondition: {
                    maxSize: 30*1024
                }
            }
        }
Copy the code

2.8 Asset handles font ICONS:

Add the following rules:

/ / the fonts icon {test: / \. (the vera.ttf | woff2?) $/, type:'asset/resource', generator:{ filename:'font/[name].[hash:3][ext]' }, }Copy the code

2.9 Use of Webpack plug-in:

As we all know, plug-ins help us do more things more easily.

2.9.1 Dist Automatic Directory Clearing plug-in:

Every time we repack the webpack, we need to delete the dist directory that we packed last time. Please download a dist directory auto-clearing plug-in here. Later packaging will default to the last packaging content empty packaging.

Install the clean-webpack-plugin:

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

Set the plugins of the configuration file:

const path = require('path'); Const {CleanWebpackPlugin} = require(' cleanwebpack-plugin '); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'build.js',}, module: {... }, //2. Define plugins as plugins: [//3. Each plugins is a class, new new CleanWebpackPlugin()]};Copy the code

Each plug-in is a class, just new, you can check the official website of the corresponding plug-in, know the function of the parameters passed.

2.9.2 HTmL-webpack-plugin plugin:

Can help us generate an HTML file template in the package directory after packaging, and reference the entry file.

Install htML-webpack-plugin:

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

Set the plugins of the configuration file:

const path = require('path'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); // 1. Const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'build.js',}, module: {... }, plugins: [new CleanWebpackPlugin(), // 2. Add new HtmlWebpackPlugin()]};Copy the code

After Webpack is packed:

Default HTML content:

<! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Webpack App</title> <meta name="viewport" content="width=device-width,initial-scale=1" /> <script defer="defer" src="build.js"></script> </head> <body></body> </html>Copy the code

For HTML, there are many things you can set, such as the content of the title, and pass the corresponding parameter in the new configuration file (see the plugin website for details) :

. Plugins: [new CleanWebpackPlugin(), new HtmlWebpackPlugin({title:' Aurora Borealis night '})]Copy the code

The content of the HTML file generated after packaging:

<! DOCTYPE HTML > < HTML > <head> <meta Charset =" UTF-8 "/> <title> Northern Lights Night. </title> <meta name="viewport" content="width=device-width,initial-scale=1" /> <script defer="defer" src="build.js"></script> </head> <body></body> </html>Copy the code

Of course, you can provide your own HTML template and generate a new HTML template based on the template I provided:

1. Create a public directory under SRC and create an index.html file as the template:

2. For example, the contents of index.html are as follows:

<! 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 > < % = htmlWebpackPlugin. Options. The title % > < / title > < / head > < body > < div class =" app" id="app">test</div> </body> </html>Copy the code

% > < % = htmlWebpackPlugin. Options. The title says use of the title in the configuration.

3. Add the template parameter, whose value is template path:

New HtmlWebpackPlugin({title:' Aurora borealis night. ', template:'./public/index.html' })Copy the code

4. Packing results:

2.10 Babel-loader handling JS compatibility:

Can handle JS compatibility issues, such as es6 compatible syntax.

Installation:

npm i @babel/core -D
npm i babel-loader -D
Copy the code

Create a new babel.config.js file at the same level as index.js to write configuration: babel.config.js

module.exports = {
    presets: ['@babel/preset-env']
}
Copy the code

Then add the rule to the webpack.config.js configuration file:

{
            test:/\.js$/,
            use:['babel-loader']
        }
Copy the code

As with postCSs-loader, write compatibility conditions in the.browserslistrc file, such as:

0.1%

last 2 version

not dead

Finally, webpack is ready.

2.11 Js compatibility with Polyfill processing:

Babel-loader does not have enough JS compatibility to handle simple ones, and if there are promises, the new syntax is not very good. So polyfill is needed.

Installation:

npm i @babel/polyfill --save
Copy the code

Modify the Babel. Config. Js:

module.exports = {
    presets: [
        '@babel/preset-env',
        {
            useBuiltIns: 'entry',
            crorejs: 3
        }
    ]
}
Copy the code

2.12 Automatic Update:

Can realize you modify the source code, the packaged code also automatically updated, do not have to manually package to update every time.

1. Before using webpack-dev-serve, you can add the watch attribute to true in the configuration file to achieve automatic update, but the performance is not good, can not be partial update, is the update of all updates:

Such as:

Module.exports = {watch: true, //path file path entry: './ SRC /index.js', //path file path, filename filename output: Resolve (__dirname, 'dist'), filename: 'build.js', //assetModuleFilename:'img/[name].[Hash :6][ext]'},... Slightly}Copy the code

2. Webpack-dev-serve has good performance and can realize local update to save performance.

Install in terminal first:

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

Later, the package command will be changed to:

webpack serve
Copy the code

2.13 HMR Module Hot Replacement:

What it does: When a module changes, it repackages only that module (not all modules), greatly increasing build speed.

First configuration:

Module. exports = {target: 'web', // open HMR devServer:{hot: true}... }Copy the code

Then hot update the module that needs hot update through judgment in the entry file:

import './title'
if(module.hot){
  module.not.accept(['./title.js'])
}
Copy the code

2.14 Path of output:

Output has a publicPath property, which is the base path for references to CSS, js, img, and other resources in a project. It outputs the directory of the parse file, specifies the directory referenced by the resource file, and is a common part of the url path for the browser to access the service after packaging.

 output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'build.js',
    publicPath:''
  },
Copy the code

2.15 Common devServer Configurations:

DevServer :{hot: true hotOnly:true, // Default port:4000 // Automatically open the browser open:false // Enable the server compress: HTML historyApiFallback: true}Copy the code

2.16 Proxy:

Webpack setup agent solves browser cross domain issues. Add a proxy attribute under devServer:

devServer:{ .... Proxy: {// define a flag, such as future API-starting requests go through the proxy's setting '/ API ': {// the actual server base address to be requested is equivalent to/API replacing target: 'https://.. '. // pathRewrite: {"^/ API ":""}, // The host in the request header will be set to target changeOrigin: true}}}Copy the code

At this point, if the server address we originally wanted to request was https://… /user can be replaced with/API /user, and the/API can be written as empty, which is equivalent to writing https://… / user, such as:

axios.get('/api/user').then(res=>{... })Copy the code

2.17 Mode Mode:

Provides a mode configuration option that tells WebPack to use some of the built-in optimizations for the corresponding mode. If not, Webpack sets the default value of mode to Production.

string = 'production': 'none' | 'development' | 'production'
module.exports = {
  mode: 'development',
};
Copy the code

2.18 Packing vue Files:

1. Installation:

$ cnpm i vue-loader vue-template-compiler -D
Copy the code

2. Add rules:

{
            test:/\.vue$/,
            use:['vue-loader']
        }
Copy the code

3. Import the plug-in and use:

const VueLoaderPlugin = require('vue-loader/lib/plugin');
Copy the code

Not finished, still updated…

Click to follow, the first time to learn about Huawei cloud fresh technology ~