Js Tree Shaking
tree shaking 是一个术语,通常用于描述移除 JavaScript 上下文中的未引用代码(dead-code)。它依赖于 ES2015 模块系统中的静态结构特性,例如 import 和 export。这个术语和概念实际上是兴起于 ES2015 模块打包工具 rollup。
webpack 2 正式版本内置支持 ES2015 模块(也叫做 harmony 模块)和未引用模块检测能力。新的 webpack 4 正式版本,扩展了这个检测能力,通过 package.json 的 "sideEffects" 属性作为标记,向 compiler 提供提示,表明项目中的哪些文件是 “pure(纯的 ES2015 模块)”,由此可以安全地删除文件中未使用的部分。
本地 tree shaking
在webpack build之后会有 unused harmony export square 表示代码没有适用.
如何删除第三方代码库中的多余代码?
比如只使用了第三库中的一个方法,以lodash为例子, 通过webpack.uifyJSPlugin ()不能完全摇掉废弃代码,需要安装特殊的babel插件 plugin-lodash
css Tree Shaking 废弃样式
需要借助Purify Css
PurifyCss-webpack
const path = require('path');const glob = require('glob');const ExtractTextPlugin = require('extract-text-webpack-plugin');const PurifyCSSPlugin = require('purifycss-webpack');module.exports = {entry: {...},output: {...},module: {rules: [{test: /\.css$/,loader: ExtractTextPlugin.extract({fallbackLoader: 'style-loader',loader: 'css-loader'})}]},plugins: [new ExtractTextPlugin('[name].[contenthash].css'),// Make sure this is after ExtractTextPlugin!new PurifyCSSPlugin({// Give paths to parse for rules. These should be absolute!paths: glob.sync(path.join(__dirname, 'app/*.html')),})]};
注意必须将PurifyCSSPlugin放在ExtractTextPlugin之后
