webpack personal notes

In essence, webpack is a static module bundler for modern JavaScript applications.

When webpack processes an application, it recursively builds a dependency graph that contains each module required by the application, and then packages all these modules into one or more bundle s.

install

md mypack
//New folder

cd mypack
// Enter your project directory mypack directory, and you can create it yourself

npm init  
//  Initializing the project folder creates a package js

//Local installation
npm install --save-dev webpack
npm install --save-dev webpack-cli

prepare documents

-- dist File generation directory
---- index.html 

-- index.js Main entry file
-- header.js Need to be index Imported files


#  index.html
<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>first webpack page</title>
</head>
<body>
 <script src="main.js"></script>   
</body>
</html>
<!--Packed js The default name is main.js-->


#  index.js
import {header} from './header.js'
document.body.append(header);


#  header.js
var header =document.createElement("div");
header.innerHTML="Hello webpack from header";
export {header};

Use profile

Create a new webpack in the project directory config. JS webpack default configuration file

const path = require('path')
// The path module of node is introduced

module.exports={
    entry:'./index.js',
    // Specify the entry of the file
    output:{
        filename:'main.js',
        // Define file name
        path:path.resolve(__dirname,'dist')
        // Define folder 
        // __ dirname get current directory
        // path. The resolve method resolves a sequence of paths or path fragments into absolute paths
    }
    // Specify the packaged exit
}
// module. The meaning of export module in export node

# The following is the pure version
const path = require('path')
module.exports={
    entry:'./index.js',
    output:{
        filename:'main.js',
        path:__dirname+'/dist',
    }
}

Core concepts: entry, output, mode mode, loader loader, plugins plug-in

output:

{
path:__dirname+"/dist",
filename:"main.js"
}

mode:

mode: "development", //Development mode
mode: "production", //Product model

Loader loader:

Definition: let webpack have the ability to handle non js files

Style loader: insert css into style tag, css loader: load css

Installation:

npm i style-loader css-loader -D

Profile:

// modular
	module:{
		// rule
		rules:[
			{
			//Testing End of css file
			test:/\.css$/,
			// Using two loader loaders
			use:["style-loader","css-loader"],
			
			}
		]
	}

plugins plug-in:

Definition: additional operations during external webpack processing, such as loading templates, compression, server, etc....

1,html-webpack-plugin: 

Load the html template file into the dist directory and insert the packaged js

Installation:

npm i html-webpack-plugin

to configure:

const htmlWebpackPlugin = require("html-webpack-plugin")

plugins:[
    new htmlWebpackPlugin({
        template:"./public/index.html"
     })
]

2. File loader: loading files
URL loader: Based on file loader # if the file is small, convert it to base64 format to reduce the number of http requests

Installation:

npm i file-loader url-loader -D

3. Clean webpack plugin: clean up the dist directory

Installation:

npm i clean-webpack-plugin -D

4. Optimize css assets webpack plugin: optimize css plug-ins

Installation:

npm i optimize-css-assets-webpack-plug -D

Import:

const optimizeCss = require('optimize-css-assets-webpack-plugin')

use:

// Optimization options
	optimization: {
		// compress
	    minimizer: [ new optimizeCss()],
	}, 

5. mini-css-extract-plugin: extract css files into a single file css file

Installation:

npm i mini-css-extract-plugin -D 

Import:

const miniCssExtractPlugin=require('mini-css-extract-plugin')

Using loader:

use:[miniCssExtractPlugin.loader,"css-loader"],

Using plug-ins:

new miniCssExtractPlugin({
			filename:"style-[hash:7].css"
		})

6. Optimize css assets webpack plugin: css optimization

Terser webpack plugin: js compression optimization

Installation:

npm i optimize-css-assets-webpack-plugin -D
npm i  terser-webpack-plugin -D

Import:

// Using css optimization plug-ins
const optimizeCss = require('optimize-css-assets-webpack-plugin')
// Extract css as a single file
const miniCssExtractPlugin=require('mini-css-extract-plugin')
// Import js compression plug-in
const TerserPlugin = require("terser-webpack-plugin");

use:

// Optimization options
    optimization: {
        // compress
        minimize: true,
        // Specify compressor
        minimizer: [ 
            new optimizeCss(),
            new TerserPlugin()
            ],
    }, 

Local server

Function: start a server locally

Installation:

npm i webpack-dev-server

to configure:

devServer:{
		open:true,//Open browser automatically
		hot:true,//Hot renewal
		host:"localhost",//Local domain name
		port:8080,//Port number
		proxy:{}//Same as Vue config. Agent configuration in JS
	}

package.json

script
"serve":"webpack server",

Start command:

npm run serve

webpack optimization

1. Hash hash:

If the content is the same, the file name is the same. If the browser has requested the same name, the browser's second request will be fetched from the cache

hash # package changes to calculate a paragraph of characters
contentHash , calculate a character according to the change of content
chunkHash calculates a string according to the entry file

2. Compression:

Compress css: optimize css assets webpack plug
Compression js: terser webpack plugin

3. Split:

Large file split:

optimization: {
		// Code segmentation
		splitChunks: {
		    chunks: "all", 
		},
}
filename:'[name]-[hash:7].js'

4,soureMap:

Source code correspondence (error)

devtool:'eval-cheap-source-map',

5. Tree shake function

Function: useless modules are not imported

optimization: {
		usedExports: true,
}

//package. Which JSON configuration files are not shaken out
"sideEffects":["@babel/polly-fill","*.css"],

6. Asynchronous loading

pic.onclick = function(){
	import(/* webpackChunkName:"jquery", webpackPrefetch: true*/"jquery")
	.then(({default:$})=>{
		// After jq is loaded, click red to display its text
		$(".red").click(function(){
			alert($(this).text())
		})
	})
}

7. Preload prefetch

import(/* webpackChunkName:"jquery", webpackPrefetch: true*/"jquery")

webpack magic note:
/ * webpackChunkName:"jquery" * / the packaged name of the imported file
/ * webpackPrefetch: true * / download the file in advance when the network is free

8. Import on demand

@Babel / plugin syntax dynamic importvue and element UI need to be downloaded on demand

To configure babelrc plugins:

{
  "presets": ["@babel/preset-env","@babel/preset-react"],
  "plugins":["@babel/plugin-syntax-dynamic-import"]
 }

Multi entry packaging

1. Configure the entrance
 

entry:{
        "vue":"./src/main.js",
        "base":"./src/index.js"
    },

2. Configure HTML webpack plugin

new htmlWebpackPlugin({
            // Specify template address
            template:"./public/index.html",
            // Which entry files generate js to insert into the current template
            chunks:["vue"],
            // Title parameter passed in template
            title: 'vue-webpack',
            // Package generated file name
            filename: 'index.html'
        }),
        new htmlWebpackPlugin({
            // Specify template address
            template:"./public/base.html",
             chunks:["base"],
             title: 'Basics webpack',
              filename: 'base.html'
        }),


 

Keywords: Javascript node.js Front-end Webpack

Added by inferium on Thu, 30 Dec 2021 17:01:49 +0200