Front end learning notes Webpack

Keywords: Javascript Front-end Webpack

Front end learning notes Webpack

1. Introduction to webpack

This section gives a brief introduction to Webpack.

1.1 basic introduction

Webpack:

A front-end resource building tool, a static module bundler.

In the view of webpack, all resource files (js/json/css/img/less /...) of the front end will be processed as modules.

It will perform static analysis according to the dependency of the module and package the corresponding static resources (bundles).

1.2 five core concepts

  • entry: indicates which file is the starting point for webpack to start packaging, analyze and build the internal dependency diagram.

  • output: indicates where and how to name the resource bundles packaged by the webpack.

  • module: enables webpack to handle non JS files, such as style files and picture files (webpack only understands
    JS)

  • plugins: can be used to perform a wider range of tasks. Plug ins range from packaging optimization and compression,
    Until the variables in the environment are redefined.

  • Mode: indicates that the webpack uses the configuration of the corresponding mode.

parameterdescribecharacteristic
developmentThe value of process.env.NODE_ENV in DefinePlugin is set to development. NamedChunksPlugin and NamedModulesPlugin are enabled.An environment in which code can be debugged and run locally
productionThe value of process.env.NODE_ENV in DefinePlugin is set to production. Enable flagdependencyusageplugin, flagincludedchunkplugin, moduleconcatenationplugin, noemitonerrorsplugin, occurrenceorderplugin, sideeffectsflagplugin and TerserPlugin.Environment that allows code optimization to run online

2. Webpack initial experience

This section describes the configuration of webpack.

2.1 initialization configuration

  1. Initialize package.json: npm init

  2. Download and install webpack: (webpack cli needs to be installed globally / locally for versions above webpack 4)

    Global installation: cnpm I webpack webpack cli - G

    Local installation: cnpm I webpack webpack cli - D

2.2 compiling and packaging applications

After creating JS and other files under src, you do not need to configure the webpack.config.js file. You can compile and package them on the command line.

  • Operation instruction:
(1)development environment (development): 
	-Command: webpack ./src/index.js -o ./build --mode=development
	-meaning: webpack with./src/index.js Start packaging for the entry file and output it to./build/main.js. The overall packaging environment is the development environment
	
(2)production environment (production): 
	-Command: webpack ./src/index.js -o ./build --mode=production
	-meaning: webpack with./src/index.js Start packaging for the entry file and output it to./build/main.js. The overall packaging environment is the production environment

(3)Import packaged resources:
	<body>
		<script src="main.js"></script>
	</body>
  • Conclusion:
  1. webpack itself can handle js/json resources, not css/img and other resources
  2. The production environment and development environment compile ES6 modularization into modularization that can be recognized by the browser, but they can not process the basic syntax of ES6 into ES5 (with the help of loader)
  3. The production environment has one more compressed js code than the development environment

3. Webpack development environment - basic configuration

This section includes the basic configuration of webpack in the development - development environment.

  • Concept:

    • index.js: Webpack common entry starting point file.
    • webpack.config.js: configuration file of webpack.
  • Main instructions:

    // Output the packaging results to the destination folder (configured in webpack.config.js)
    > webpack 
    
    // Only compile and package in memory without output
    > npx webpack-dev-server
    
  • Purpose: mainly to make the code run. Mainly consider the following aspects:

    • Packaging style resources (3.1)
    • Packaging HTML resources (3.2)
    • Package picture resources (3.3)
    • Package other resources (3.4)
    • devServer(3.5)
  • Function: indicates what the webpack does (the configuration will be loaded when the webpack instruction is run)

  • Note: all build tools are run based on node.js platform, and common.js is adopted by default for modularization.

  • Differences between loader and plugin:

    • Loader: 1. Download 2. Use (configure loader)
    • plugins: 1. Download 2. Import 3. Use

The following is an overview of the structure of the webpack.config.js file.

/* Various resources are usually introduced here */

// webpack config
module.exports = {

    /* entry: The parameter configuration of the entry file from which the webpack is packaged */
    entry: '',
    
    /* output: Output file parameter configuration */
    output: {
  	    // Output file name 
        filename: '',
        // Output file path
        path: resolve(...)
    },
    
    /* module: loader to configure */
    module: {
        /* loader Object configuration details */
        rules: [
            // Each loader object
            {
                // File name format of processing object
                test: ...,
                // Which loaders are used for processing, and the execution order of loaders is from right to left and from bottom to top
                use: [...]
            },
            {...}
        ]
    },
  
    /* plugins: Plug in configuration */
    plugins: [...],
  
    /* mode: Environment mode configuration - development | production */
    mode: 'development'
  
}

3.1 style resources

This section includes related webpack configuration examples for packaging style resources.

// resolve the method used to splice absolute paths
const {resolve} = require('path')

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        // _dirname is a nodejs variable, which represents the absolute directory path of the current file
        path: resolve(__dirname, 'build')
    },
    module: {
        rules: [
            { // css-loader
                // \. is equivalent to. $stands for what ends / as the escape character
                test: /\.css$/,
                use: [
                    // Create a style tag, insert the style resource in js, and add it to the head to take effect
                    'style-loader',
                    // Change the css file into a commonjs module and load it into js, with the content as a style string
                    'css-loader',
                ]
            },      
            { // less-loader
                test: /\.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    // Compile less files into css files
                    'less-loader'
                ]
            }
        ]
    },
    plugins: [],
    mode: 'development'
}

3.2 HTML resources

This section includes related webpack configuration examples for packaging HTML resources.

// html-webpack-plugin
// Function: create an empty HTML by default and automatically import all resources (js/css) for packaged output
// Requirements: structured HTML files
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {resolve} = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: "main.js",
        path: resolve(__dirname, 'build')
    },
    module: {
        rules: []
    },
    plugins: [
        new HtmlWebpackPlugin({
            // Copy the files in the template and automatically import all resources (js/css) for packaged output
            template: "./src/index.html"
        })
    ],
    mode: "development"
}
       rules: []
    },
    plugins: [
        new HtmlWebpackPlugin({
            // Copy the files in the template and automatically import all resources (js/css) for packaged output
            template: "./src/index.html"
        })
    ],
    mode: "development"
}

Posted by dennismcdougall on Thu, 04 Nov 2021 03:46:53 -0700