Teach you to use webpack from scratch, so don’t worry about packaging the project from now on

webpack

  • Problem
    File dependencies are intricate,
    static file requests are inefficient,
    modular support is not friendly, and
    browsers are not compatible with advanced JS features

Installation and configuration

--save-dev 也可以写作 -D,表示是开发依赖(开发阶段需要用到的包,项目上线运行后不需要)

Initialize the project npm init -y

Create a new src directory under the following directory as the code file directory

Create index.html and index.js under src

Write html code in index.html

Install jquerynpm i jquery

Insert picture description here

Install webpack
through the command npm install webpack webpack-cli --save-devto install

webpack configuration
Create a new webpack.config.js in the root directory

module.exports={
    mode:'development' // 开发模式
}
Insert picture description here


Configure the startup command
Open package.json and add the following code in the scripts property

"dev":"webpack"

Insert picture description here


Package the
terminal to run the following command
npm run dev
after success, it will create a dist directory in the following directory, and generate a main.js file.
Run
in index.html, import main.js, and run index.html again to succeed

Package entry files and export files

  • Entry file

It is the first file accessed when the project or program is requested. This file will find the corresponding module for processing

In the current project, index.html is the entry file, because we are requesting index.html

But for webpack, the packaged entry file is index.js, because index.js introduces modules required by other programs and writes the corresponding logic code

  • export documents

File directory and name after packaging

webpack has some default configurations

Entry file: src/index.js
Export file: /dist/main.js
Reconfigure entry file and export file

const path=require('path')
module.exports={
    mode:'development', // 开发模式
    entry:path.resolve(__dirname,'./src/index.js'),
    output:{
        path:path.resolve(__dirname,'./dist'),
        filename:"bundle.js"
    }
}

Run npm run devcommand to view the results

A dist file will be automatically created in the root directory, and the bundle.js file will be generated inside

Insert picture description here

Automatic packaging

installation
npm install --save-dev webpack-dev-server

Modify the startup command in pacjkage.json
"dev":"webpack serve --open"

Or use (–open is to open the browser automatically, you don’t need to add it) to
"dev":"webpack serve"

Insert picture description here


run
npm run dev

The opening address is: The http://localhost:8080/

Insert picture description here


js file introduced in the original index.html is as shown below:

Insert picture description here


After running, there is http://localhost:8080/no need to make any changes, the browser will make changes according to the content

Generate preview page

The current problem: localhost:8080 corresponds to the website and the directory, index.html is in the src directory, which is troublesome to access

Solution: You can copy index.html in the src directory to the root directory, so that when you access localhost:8080, index.html will be rendered by default

But if it is troublesome to manually copy after modifying index.html, you can use the plug-in: HtmlWebpackPlugin

installation
npm install --save-dev html-webpack-plugin

After the installation is complete, write the following code in webpack.config.js and

Insert picture description here


re-run npm run devit will report the following error

Insert picture description here


. This error is reported because we lack loader-utils dependency

Execute the following code to solve the above error problem

npm install loader-utils -D

After re-running npm run dev again

Visit: http://localhost:8080/, index.html will run

But there is no index.html in the root directory, because it is still created in memory

But you will find that there is a js file imported by yourself (it is invalid), and the system will automatically import the bundle.js file in the root directory to you

Insert picture description here

Loader

By default, webpack can only package .js module files. Other static files, such as .css, pictures, etc. cannot be processed by default. If the corresponding loader is not loaded, an error will be reported.

webpack supports the use of loader to preprocess files. You can build any static resources including JavaScript. And you can easily write your own loade using Node.js

The figure below illustrates how webpak handles various file types

Insert picture description here

Process the css file

Create a new css directory under the src directory, and create a new index.css

Writing style

* {
    margin: 0;
    padding: 0;
}

ul {
    list-style-type: none;
}

li {
    line-height: 45px;
}
Insert picture description here


However, the following error will be reported during packaging. It can be

Insert picture description here


seen that there is no corresponding loader, and webpack cannot process the css file when packaging.

Install the loader corresponding to the css style

npm install --save-dev css-loader style-loader

Configure webpack.config.js

Insert picture description here


and re-run npm run dev after configuration

Note:

Insert picture description here


These two cannot be reversed (the call of loader is dropped from back to front)

Process less files

installation

npm install less-loader less -D

Add a

Insert picture description here


new inde.less to the css directory in rules

body {
    background-color: #ccc;

    ul {
        list-style-type: none;

        li {
            line-height: 35px;
        }
    }

}

Some plug-ins may be added to our vscode to automatically convert less files into css files. You can turn it off for better results.

Inde.less is introduced in index.js to

Insert picture description here


re-runnpm run dev

Insert picture description here

Picture processing

installation
npm i url-loader url-loader -D

Configure webpack.config.js

{
    test: /\.jpg|png|gif|bmp|jfif|ttf|eot|svg|woff|woff2$/,
    use: [{
        loader: 'url-loader',
        options: {
            limit: 614400 // 代码中使用的图片为500k
        }
    }]
}
Insert picture description here


Put a picture in the new folder images in src.

Insert picture description here


Set this picture to the body as the background. After the

Insert picture description here


configuration is completed, it must be re-run. npm run dev
If the picture is larger than the size we set, the resource file will be returned.
If the picture is smaller than the size we set, return Base64 encoding

About base64 encoding of pictures

The base64 encoding of a picture is to encode a picture data into a string of strings, and use this string to replace the image address
.
What's the point of doing this? We know that every picture on the webpage we see needs to be downloaded from an http request (all the csssprites technology came into being, but csssprites has its own limitations, which will be mentioned below )
.
Yes, no matter what, the download of the picture always has to send a request to the server. If the download of the picture does not have to send a request to the server, but it can be downloaded to the local at the same time as the HTML download, that’s great, and base64 just can solve this problem

Processing advanced js syntax

Babel is used to convert the new grammar and features of js into the grammar supported by the browser

Install babel converter related packages

npm install -D babel-loader @babel/core @babel/preset-env

Add the following rules in webpack.config.js

{
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
        loader: 'babel-loader',
        options: {
        presets: ['@babel/preset-env']
        }
    }
}
Insert picture description here


Write the following code in index.js

class Person {
    static age = 20
}
console.log(Person.age);

Re-run npm run devfor packaging

The following error will be reported. The

Insert picture description here


reason for the error is that the relevant plug-in for babel syntax is not installed.

installation
npm i -D @babel/plugin-proposal-class-properties

Then add configuration in the option attribute of the above rule

options: {
    presets: ['@babel/preset-env'],
    plugins: ['@babel/plugin-proposal-class-properties'] // 新加的配置
}
Insert picture description here


Re-run again to npm run devpackage it.