The most complete summary of webpack

webpack

install

Before installation, initialize the project to generate package JSON file

npm init -y 
npm init 

Next, install webpack and webpack cli

npm i webpack webpack-cli --save

Configure command line

In package The startup command is configured in the scripts field of the JSON file

"scripts":{
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"webpack --mode development",
    "build":"webpack --mode production",
}

Create entry file

The default entry file for webpack is index. In the src directory js;
You need to create the src folder in the root directory of the project, and create the index JS file as the entry file

Execute command

After the command is executed successfully. A dist file will be automatically generated in the root directory of the project, which is the packaged product; Dist files are not required and can be deleted at any time

  1. development environment
npm run dev
  1. production environment
npm run build

Modularity supported by webpack

webpack supports CommonJs modularization and es6 modularization

  1. CommonJs
// Module export
module.exports = {}
//  Module import
const res = requrie('modular url')
  1. es6
//  Module export
export default Module name
export Module object

//  Module import
import  ... from 'modular url'

Configuration file for webpack

If you want to configure the webpack, you need to create the configuration file webpack. Net under the project root directory config. js; This file is a module

module.exports = {
    ...
}

Entrance and exit of webpack

webpack entry and exit output:

  1. Single inlet and outlet
//  Single inlet and outlet
const path = require('path')
module.exports = {
    entry:'index.js',
    output:{
        //  Set the directory where the value export file is stored
        path:path.resolve(__dirname, "dist"),
        //  Configure the output file name. You can specify a file name or use automatic mapping [name]
        filename:'[name].js'
    }
}
  1. Multiple entry files and single exit
//  Multiple entry files and single exit
const path = require('path')
module.exports = {
    entry:['index.js', 'main.js',...],
    output:{
        //  Set the directory where the value export file is stored
        path:path.resolve(__dirname, "dist"),
        //  Configure the output file name. You can specify a file name or use automatic mapping [name]
        filename:'[name].js'
    }
}
  1. Multi entry configuration
const path = require('path')
module.exports = {
    entry:{
        index:'index.js',
        main:'main.js'
    }
    output:{
        //  Set the directory where the value export file is stored
        path:path.resolve(__dirname, "dist"),
        //  Automatic mapping [name] can also be used for the configuration output file name. Name corresponds to the key in the entry
        filename:'[name].js'
    }
}

loader and plugin of webpack

webpack processing template file

Webpack handles html files: we need to use the html webpack plugin plug-in, which will automatically help us manage the imported js files

  1. Install plug-ins
npm i html-webpack-plugin --save
  1. Configure plug-ins
//  1. Introduction of plug-ins
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        })
    ]
}

Manage output folder dist

To manage the output file dist, you can automatically manage the dist folder through configuration items or plug-ins

  1. Configuration item
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js',
        //  Manage dist folders
        clean:true
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        })
    ]
}
  1. Through plug-ins
    The clean webpack plugin plug-in needs to be installed
npm i clean-webpack-plugin --save
const HtmlWebpackPlugin = require('html-webpack-plugin')
const  { CleabWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js',
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new CleabWebpackPlugin()
    ]
}

webpack handles css files

When webpack processes css / sass files, it needs to rely on the loader; CSS loader and style loader, sass loader and sass need to be installed

Function of loader:

  1. css loader: process and parse css files
  2. Style loader: extract the parsed css file from the js file and insert it into the html page in an internal style (style tag),
  3. Sass: parsing sass files
  4. Sass loader: compile and transcode to css file

---------------------------------—

Generate internal css Styles

  1. Install loader
npm i css-loader style-loader sass-loader sass --save
  1. Configure loader
//  1. Introduction of plug-ins
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                use:['style-loader', 'css-loader']
            },
            {
                test:/\.(scss|sass)$/i,
                use:['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        })
    ]
}

Package to generate independent css files

To package and generate independent css files, you need to use the mini css extract plugin plug-in,

  1. install
npm install --save-dev mini-css-extract-plugin
  1. Configure plug-ins
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                // Use the loader inside the plug-in to generate a separate css file
                use:[MiniCssExtractPlugin.loader 'css-loader']
            },
            {
                test:/\.(scss|sass)$/i,
                use:[MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new MiniCssExtractPlugin()
    ]
}

webpack handles picture resources

To process image resources, webpack needs to use file loader and URL loader

  1. install
npm i file-loader url-loader --save
  1. Configure loader
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                // Use the loader inside the plug-in to generate a separate css file
                use:[MiniCssExtractPlugin.loader 'css-loader']
            },
            {
                test:/\.(scss|sass)/i,
                use:[MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            },
            //  Configure the loader for processing pictures
            {
                test:/\.(jpg|jpeg|png|gif|webp)$/i,
                use:[
                    {
                        loader:'url-loader',
                        options:{
                            //  limit limits the size of the picture. If it is less than the specified value, it will be converted to base64 encoding format
                            limit:8192,
                            // The name attribute configures the entered picture name and path
                            name:'image/[name].[ext]'
                        }
                    }
                ]
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new MiniCssExtractPlugin()
    ]
}

Hot update of webpack

The webpack dev server plug-in of webpack can realize hot update and start service

  1. install
npm i webpack-dev-server --save
  1. Configure devServer
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    devServer:{
        // Port number to open the service
        port:9001
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                // Use the loader inside the plug-in to generate a separate css file
                use:[MiniCssExtractPlugin.loader 'css-loader']
            },
            {
                test:/\.(scss|sass)/i,
                use:[MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            },
            //  Configure the loader for processing pictures
            {
                test:/\.(jpg|jpeg|png|gif|webp)$/i,
                use:[
                    {
                        loader:'url-loader',
                        options:{
                            //  limit limits the size of the picture. If it is less than the specified value, it will be converted to base64 encoding format
                            limit:8192,
                            // The name attribute configures the entered picture name and path
                            name:'image/[name].[ext]'
                        }
                    }
                ]
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new MiniCssExtractPlugin()
    ]
}
  1. Configure startup command
    In package Configure the startup command in the JSON file and execute the command npm run server
"scripts":{
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"webpack --mode development",
    "build":"webpack --mode production",
    "server":"webpack serve --open"
}

Environment configuration of webpack

The environment is divided into development environment, production environment, test environment, etc., so the environment needs to be configured

We need to use the plug-in webpack merge to help us merge and process the configuration files:

npm i webpack-merge --save

Create three configuration files for webpack: webpack basic. js webpack. dev.js webpack. pro. js

  • webpack.basic.js

  • webpack.dev.js

const { merge } = require('webpack-merge');
const basic = require('webpack.basic.js');
module.exports = merge(basic, {...})
  • webpack.pro.js
const { merge } = require('webpack-merge');
const basic = require('webpack.basic.js');
module.exports = merge(basic, {...})

webpack

install

Before installation, initialize the project to generate package JSON file

npm init -y 
npm init 

Next, install webpack and webpack cli

npm i webpack webpack-cli --save

Configure command line

In package The startup command is configured in the scripts field of the JSON file

"scripts":{
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"webpack --mode development",
    "build":"webpack --mode production",
}

Create entry file

The default entry file for webpack is index. In the src directory js;
You need to create the src folder in the root directory of the project, and create the index JS file as the entry file

Execute command

After the command is executed successfully. A dist file will be automatically generated in the root directory of the project, which is the packaged product; Dist files are not required and can be deleted at any time

  1. development environment
npm run dev
  1. production environment
npm run build

Modularity supported by webpack

webpack supports CommonJs modularization and es6 modularization

  1. CommonJs
// Module export
module.exports = {}
//  Module import
const res = requrie('modular url')
  1. es6
//  Module export
export default Module name
export Module object

//  Module import
import  ... from 'modular url'

Configuration file for webpack

If you want to configure the webpack, you need to create the configuration file webpack. Net under the project root directory config. js; This file is a module

module.exports = {
    ...
}

Entrance and exit of webpack

webpack entry and exit output:

  1. Single inlet and outlet
//  Single inlet and outlet
const path = require('path')
module.exports = {
    entry:'index.js',
    output:{
        //  Set the directory where the value export file is stored
        path:path.resolve(__dirname, "dist"),
        //  Configure the output file name. You can specify a file name or use automatic mapping [name]
        filename:'[name].js'
    }
}
  1. Multiple entry files and single exit
//  Multiple entry files and single exit
const path = require('path')
module.exports = {
    entry:['index.js', 'main.js',...],
    output:{
        //  Set the directory where the value export file is stored
        path:path.resolve(__dirname, "dist"),
        //  Configure the output file name. You can specify a file name or use automatic mapping [name]
        filename:'[name].js'
    }
}
  1. Multi entry configuration
const path = require('path')
module.exports = {
    entry:{
        index:'index.js',
        main:'main.js'
    }
    output:{
        //  Set the directory where the value export file is stored
        path:path.resolve(__dirname, "dist"),
        //  Automatic mapping [name] can also be used for the configuration output file name. Name corresponds to the key in the entry
        filename:'[name].js'
    }
}

loader and plugin of webpack

webpack processing template file

Webpack handles html files: we need to use the html webpack plugin plug-in, which will automatically help us manage the imported js files

  1. Install plug-ins
npm i html-webpack-plugin --save
  1. Configure plug-ins
//  1. Introduction of plug-ins
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        })
    ]
}

Manage output folder dist

To manage the output file dist, you can automatically manage the dist folder through configuration items or plug-ins

  1. Configuration item
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js',
        //  Manage dist folders
        clean:true
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        })
    ]
}
  1. Through plug-ins
    The clean webpack plugin plug-in needs to be installed
npm i clean-webpack-plugin --save
const HtmlWebpackPlugin = require('html-webpack-plugin')
const  { CleabWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js',
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new CleabWebpackPlugin()
    ]
}

webpack handles css files

When webpack processes css / sass files, it needs to rely on the loader; CSS loader and style loader, sass loader and sass need to be installed

Function of loader:

  1. css loader: process and parse css files
  2. Style loader: extract the parsed css file from the js file and insert it into the html page in an internal style (style tag),
  3. Sass: parsing sass files
  4. Sass loader: compile and transcode to css file

---------------------------------—

Generate internal css Styles

  1. Install loader
npm i css-loader style-loader sass-loader sass --save
  1. Configure loader
//  1. Introduction of plug-ins
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                use:['style-loader', 'css-loader']
            },
            {
                test:/\.(scss|sass)$/i,
                use:['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        })
    ]
}

Package to generate independent css files

To package and generate independent css files, you need to use the mini css extract plugin plug-in,

  1. install
npm install --save-dev mini-css-extract-plugin
  1. Configure plug-ins
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                // Use the loader inside the plug-in to generate a separate css file
                use:[MiniCssExtractPlugin.loader 'css-loader']
            },
            {
                test:/\.(scss|sass)$/i,
                use:[MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new MiniCssExtractPlugin()
    ]
}

webpack handles picture resources

To process image resources, webpack needs to use file loader and URL loader

  1. install
npm i file-loader url-loader --save
  1. Configure loader
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                // Use the loader inside the plug-in to generate a separate css file
                use:[MiniCssExtractPlugin.loader 'css-loader']
            },
            {
                test:/\.(scss|sass)/i,
                use:[MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            },
            //  Configure the loader for processing pictures
            {
                test:/\.(jpg|jpeg|png|gif|webp)$/i,
                use:[
                    {
                        loader:'url-loader',
                        options:{
                            //  limit limits the size of the picture. If it is less than the specified value, it will be converted to base64 encoding format
                            limit:8192,
                            // The name attribute configures the entered picture name and path
                            name:'image/[name].[ext]'
                        }
                    }
                ]
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new MiniCssExtractPlugin()
    ]
}

Hot update of webpack

The webpack dev server plug-in of webpack can realize hot update and start service

  1. install
npm i webpack-dev-server --save
  1. Configure devServer
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry:'index.js',
    output:{
        path:path.resolve(__dirname, 'dist'),
        filename:'index.js'
    },
    devServer:{
        // Port number to open the service
        port:9001
    },
    module:{
        //  Configure rules. The rule has two required attributes: test (detect the matching file to be processed) and use (process the detected target file with the corresponding loader)
        rules:[
            // Each object is a configuration item of a loader
            {
                test:/\.css$/i,
                // Use the loader inside the plug-in to generate a separate css file
                use:[MiniCssExtractPlugin.loader 'css-loader']
            },
            {
                test:/\.(scss|sass)/i,
                use:[MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
            },
            //  Configure the loader for processing pictures
            {
                test:/\.(jpg|jpeg|png|gif|webp)$/i,
                use:[
                    {
                        loader:'url-loader',
                        options:{
                            //  limit limits the size of the picture. If it is less than the specified value, it will be converted to base64 encoding format
                            limit:8192,
                            // The name attribute configures the entered picture name and path
                            name:'image/[name].[ext]'
                        }
                    }
                ]
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            //  Define template
            template:'index.html',
            //  Enter file name
            filename:'index.html'    
        }),
        new MiniCssExtractPlugin()
    ]
}
  1. Configure startup command
    In package Configure the startup command in the JSON file and execute the command npm run server
"scripts":{
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"webpack --mode development",
    "build":"webpack --mode production",
    "server":"webpack serve --open"
}

Environment configuration of webpack

The environment is divided into development environment, production environment, test environment, etc., so the environment needs to be configured

We need to use the plug-in webpack merge to help us merge and process the configuration files:

npm i webpack-merge --save

Create three configuration files for webpack: webpack basic. js webpack. dev.js webpack. pro. js

  • webpack.basic.js

  • webpack.dev.js

const { merge } = require('webpack-merge');
const basic = require('webpack.basic.js');
module.exports = merge(basic, {...})
  • webpack.pro.js
const { merge } = require('webpack-merge');
const basic = require('webpack.basic.js');
module.exports = merge(basic, {...})

Keywords: Javascript Front-end Webpack

Added by rockstar_tom on Tue, 14 Dec 2021 03:25:49 +0200