webpack之tree shaking

What is the tree-shaking?

Tree-shaking in the front end can be understood as a tool by "shaking" our js file, which will be less than code "Shake" out, it is a performance optimization category. Specifically, in webpack project,
there is an entry document, the equivalent of a tree trunk, there are many entry file dependencies module, the equivalent of branches. In reality, though dependent on it for a module, but in fact only use some of these features. By
tree-shaking, the module will not shake off use, so to achieve the purpose of deleting unnecessary code.

tree-shaking principles

tree-shaking principle , in simple terms

  • Nature tree shaking is to eliminate useless Javascript code
  • Because the module appears ES6, ES6 module dependencies are determined, and regardless of the state of run-time, static analysis can be performed reliably

How to use tree-shaking?

  • Create a file tree-shaking at webpackDemo / demo, the following file directory

  • index.js follows
import {add} from "./math.js"
console.log(mathFn)
function component(){
    var element = document.createElement("pre");
    element.innerHTML = [
        "hello webpack",
        "5 cubed is equal to " + add(5,6)
    ].join("\n\n");
    return element;
}
document.body.appendChild(component())
  • math.js follows
export function add(a,b){
    console.log("add");
    return a+b;
}

export function minus(a,b){
    console.log("minus")
    return a-b
}

export function multiply(a,b){
    console.log("mutiply");
    return a*b;
}

export function divide(a,b){
    console.log("divide");
    return a/b;
}

  • tree-shaking.js follows
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
const webpack = require("webpack");
module.exports = {
    mode:"development",
    entry:path.resolve(__dirname,"src/index.js"),
    module:{
        rules:[
            {
                test:/\.m?js$/,
                exclude:/(node_modules|bower_components)/,
                use:{
                    loader:"babel-loader",
                    options:{
                        presets:["@babel/preset-env"],
                        plugins:[
                            "@babel/plugin-transform-runtime"
                        ]
                    }
                }
            }
        ]
    },
    output:{
        filename:"bundle.js",
        path:path.resolve(__dirname,"dist")
    },
    plugins:[
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin(),
//      new webpack.NamedModulesPlugin(),
//      new webpack.HotModuleReplacementPlugin()
    ],
    devtool:"inline-source-map",
//  devServer:{
//      contentBase:"./dist",
//      hot:true,
//      inline:true
//  }
}
  • package.json follows
{
  "name": "webpackDevServer",
  "sideEffects": false,
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --config demo/webpack-dev-server/webpack-dev-server.js",
    "server": "node demo/webpack-dev-middleware/server.js",
    "hmr": "webpack-dev-server  --config demo/HMR/webpack.hmr.js",
    "treeShaking:dev": "webpack-dev-server --config demo/tree-shaking/tree-shaking.js",
    "treeShaking:build": "webpack  --config demo/tree-shaking/tree-shaking.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "7.6.4",
    "@babel/plugin-transform-runtime": "^7.6.2",
    "@babel/preset-env": "^7.6.3",
    "babel-loader": "8.0.6",
    "clean-webpack-plugin": "3.0.0",
    "css-loader": "3.2.0",
    "express": "4.17.1",
    "html-webpack-plugin": "3.2.0",
    "style-loader": "1.0.0",
    "webpack": "4.41.2",
    "webpack-cli": "3.3.9",
    "webpack-dev-middleware": "3.7.2",
    "webpack-dev-server": "3.8.2"
  }
}
  • 执行 npm run treeShaking: build

Execution results are as follows

After the execution, we can see bundle.js files can be found in all of the code math.js was packed, but we only use the file add function, we do not want useless to function package to file, then we you can use the tree-shaking

  • Enable webpack
    currently used in the project is webpack4, speaking mode is set to open production tree shaking

About side effects (side effects)

Refers to the side effect in addition to the function returns a value other than any application state observed outside the function call changes. Side effects include:

  • Change any external variables or object attribute (e.g., a global variable, or a function variable on the parent scope chain)
  • Write log
  • In the screen output
  • Write file
  • Hair network requests
  • Trigger any external process
  • Another call functions with side effects

tree shaking can not automatically identify code that belongs to side effects, and therefore manually specify the code is very important, if not specified there may be some unexpected problems

In webpack, the sideeffects are achieved by the property packge.json
{
"name": "Tree-shaking",
"sideeffects": to false
}

If all the code is contained side effects, we can simply mark an attribute as false, and inform webpack, he can safely delete unused export Exports

If your code does have some side effects, it can be changed to provide an array

{
"name": "tree-shaking",
"sideEffects": [
"./src/common/polyfill.js"
]
}

to sum up

  • tree shaking does not support dynamic import (such as the CommonJS require () syntax), only supports pure static import (ES6 the import / export)
  • webpack can add a "sideEffects" property in the project package.json, the side effects of scripts manually specify

The mode changes settings in package.json in sideEffects: false results are as follows

We can see that use tree shaking, the code volume becomes small, and we cite math.js add function is switched, and other code no unreferenced

Guess you like

Origin www.cnblogs.com/dehenliu/p/12523231.html