demo10 关于JS Tree Shaking

栏目: JavaScript · 发布时间: 5年前

内容简介:借助于 es6 (es2015) 模块系统 (import 和 export) 的静态解析,webpack 能够利用 Tree Shaking 进行按需加载,移除掉没有被引用的模块,从而减少包的大小,缩小应用的加载时间,从而提高性能体验。从 webpack 4 开始,只需将

借助于 es6 (es2015) 模块系统 (import 和 export) 的静态解析,webpack 能够利用 Tree Shaking 进行按需加载,移除掉没有被引用的模块,从而减少包的大小,缩小应用的加载时间,从而提高性能体验。

2.需配合 UglifyJSPlugin 来实现 tree shaking

UglifyJSPlugin 的作用在于删除未被引用代码以及压缩代码。

从 webpack 4 开始,只需将 "mode" 设置为 "production" 模式,即可开启 UglifyJSPlugin 的功能。

详情可参考官方 Tree Shaking 文档: www.webpackjs.com/guides/tree…

3.目录结构

// `--` 代表目录, `-` 代表文件
  --demo10
    --src
      -app.js
      -module.js
    -webpack.config.js
复制代码

module.js

export const sayHello1 = () => {
  console.log('hello1');
}

export const sayHello2 = () => {
  console.log('hello2');
}

export const sayHello3 = () => {
  console.log('hello3');
}
复制代码

app.js

// 只导入了 sayHello1 ,观察打包后的 bundle 代码,移除了 sayHello2 和 sayHello3 的代码
import { sayHello1 } from './module';

sayHello1();
复制代码

4.编写webpack配置文件

webpack.config.js

const path = require("path");

module.exports = {
  mode: "production" || "development", // tree shaking 需要使用 "production" 模式
  entry: {
    app: "./src/app.js"
  },
  output: {
    publicPath: __dirname + "/dist/", // 打包后资源文件的引用会基于此路径
    path: path.resolve(__dirname, "dist"), // 打包后的输出目录
    filename: "[name].bundle.js"
  }
};
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computational Geometry

Computational Geometry

Mark de Berg、Otfried Cheong、Marc van Kreveld、Mark Overmars / Springer / 2008-4-16 / USD 49.95

This well-accepted introduction to computational geometry is a textbook for high-level undergraduate and low-level graduate courses. The focus is on algorithms and hence the book is well suited for st......一起来看看 《Computational Geometry》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试