directory

  1. DllPlugin: Creates a dynamic link library
  2. Happypack: Implement multi-threaded packaging
  3. Webpack comes with optimizations
  4. Pull out the common code
  5. Lazy loading
  6. Hot update

1. DllPlugin: Create a dynamic link library

Sample code:

// index.js
import React from 'react';
import {render} from 'react-dom';

render(<h1>Milk tea</h1>.window.root);
Copy the code

Effect:

You can see that the packaged files are a bit large because webPack also packaged the two react files that were introduced.

Create the webpack.config.react.js configuration file that configures the React package to generate the dynamic link library

let path = require('path');
let webpack = require('webpack');
module.exports = {
    mode:'development'.entry: {react: ['react'.'react-dom']./ / the entry
    },
    output: {filename:'_dll_[name].js'.// The generated file name
        path:path.resolve(__dirname,'dist'),
        library:'_dll_[name]'.// libraryTarget:'var' // Default: var
    },
    plugins: [new webpack.DllPlugin({  // Request: name == library
            name:'_dll_[name]'.path:path.resolve(__dirname,'dist'.'manifest.json')]}})Copy the code

Packaged directory structure:

_dll_react.js
manifest.json

In webpack.config.js->plugins:

new webpack.DllReferencePlugin({
    manifest:path.resolve(__dirname,'dist'.'manifest.json')}),Copy the code

Finally, the package looks like this. The file is much smaller because instead of packaging react, it references the already packaged React file.

2. Happypack: Implement multi-threaded packaging

Installation:

 npm i happypack
Copy the code

Webpack.config.js:

let Happypack = require('happypack');
Copy the code

module->rules:

rules:[
    {
        test:/\.js$/.exclude:/node_module/.// Exclude directories
        include:path.resolve('src'), // Contains the directory
        use:'Happypack/loader? id=js'}]Copy the code

plugins:

new Happypack({
    id:'js'.use: [{loader:'babel-loader'.options: {presets: ['@babel/preset-env'.'@babel/preset-react']]}}}),Copy the code

Js files are packed with Happypack/loader, and the Happypack plugin with js is called.

Results: You can see that the packaging used 3 threads, 1359ms;

Note: multithreading packaging process, multithreading operation will also consume time, the need to package small files, but more time;

The same goes for CSS multithreading packaging:

{
   test:/\.css$/.use:'Happypack/loader? id=css'
}
Copy the code
new Happypack({
    id:'css'.use: ['style-loader'.'css-loader']}),Copy the code

3. Webpack comes with optimizations

Sample code:

// test.js
let sum = (a,b) = > {
    return a+b+'sum';
}

let minus = (a,b) = > {
    return a-b+'minus';
}

export default {
    sum,minus
}
Copy the code
// index.js
import calc from './test';
console.log(calc.sum(1.2))
Copy the code

In the above code, when mode:’production’ is configured in webpack.config.js, minus is not packaged in the production environment.

Note:

  • importIn production, the behavior of automatically removing unnecessary code is also calledtree-shaking
  • The ES6 module puts the results indefaultOn,index.jsuserequireThe import should be as follows and will not automatically remove useless code
    // index.js
    const calc = require('./test');
    console.log(calc.default.sum(1.2))
    Copy the code

In production, Webpack will automatically omit the scope hosting code, as follows:

let a = 1;
let b = 2;
let c = 3;
let d = 4;
let e = a+b+c+d;
console.log(e);
Copy the code

4. Remove common code

To achieve multi-page public file module extraction



index.js
other.js
a.js
b.js
a.js
b.js

Webpack. Config. Js configuration:

optimization:{
    splitChunks: {// Split code blocks
        cacheGroups:{  / / cache group
            common:{   // Public module
                chunks:'initial'.// We need to pull away at the beginning
                minSize:0.// If the value is greater than 0 bytes, extract it
                minChunks:2 // If you use it twice or more}}}},Copy the code

Common ~index~other.js is the extracted file containing the contents of a.js and b.js.

import $ from 'jquery'
console.log($)
Copy the code

This can be configured in webpack.config.js: Vendor section configuration to remove third-party modules

optimization:{
   splitChunks: {// Split code blocks
       cacheGroups:{  / / cache group
           common:{   // Public module
               chunks:'initial'.// We need to pull away at the beginning
               minSize:0.// If the value is greater than 0 bytes, extract it
               minChunks:2 // If you use it twice or more
           },
           vendor: {priority:1.// Set the weight and remove the third module first
               test:/node_modules/.// Use it as a reference
               chunks:'initial'.// We need to pull away at the beginning
               minSize:0.// If the value is greater than 0 bytes, extract it
               minChunks:2 // If you use it twice or more}}}},Copy the code

5. A lazy loading

Lazy loading implementation:

Directory:

import
1.index.js

// index.js
let button = document.createElement('button');
button.innerHTML="Here's the button";
button.addEventListener('click'.function() {
    // Es6 syntax jSONP implements dynamic file loading
    import('./source.js').then(data= > {
        console.log(data.default); })});document.body.appendChild(button);
Copy the code
// source.js
export default 'ha ha'
Copy the code

Effect:

6. Hot update

When the module is modified, just load the updated module, without refreshing the whole page;

Webpack.config.js:

devServer:{
    hot: true.// Enable hot updates
    port:3000./ / the port number
    open:true.// Automatically open the browser
    contentBase:'./dist' // Specifies the directory where the HTML page is to be accessed
},
Copy the code

Plugins:

new webpack.NamedModulesPlugin(),  // Prints the updated module path
new webpack.HotModuleReplacementPlugin() // Hot update plugin
Copy the code

Code examples:

// index.js
import str from './source';
console.log(str);
if(module.hot){
    module.hot.accept('./source', () = > {let str = require('./source')
        console.log(str)
    })
}
Copy the code
// source.js
export default 'Ha 1111 ha.'
Copy the code

Effect demonstration: