css tree sharking

purgecss-webpack-plugin

用于完成 css tree sharking 的插件,减少部分包体积

优点

​ 可以移除无用代码

缺点

​ 1. 需要抽出 scss/css/less/styl/sass 文件 使用引入的方式而不是内联

​ 2. 无法处理的几种情况

​ 被注释的代码

​ 动态拼接的代码(情况多种)

3. 构建速度变慢,增加打包负担

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const path = require('path')
const glob = require('glob')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const PurgecssPlugin = require('purgecss-webpack-plugin')

const PATHS = {
src: path.join(__dirname, 'src')
}

module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.scss$/,
loaders: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
'postcss-loader',
'sass-loader',
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'base.[contenthash:8].css',
}),
new PurgecssPlugin({
paths: glob.sync(`${PATHS.src}/*`),
whitelist: ['whitelisted']
})
]
}

钩子介绍

1.1 compiler钩子介绍

1.2 conpilation 钩子介绍

使用到的部分钩子

compiler.hooks.compilation:当 compilation 被创建之后调用

compiler.hooks.done:编译完成后执行

compilation.hooks.additionalAssets:为编译(compilation)创建附加资源(asset)

参数介绍

compilation.assets:所有需要输出的资源会存放在 compilation.assets 中,compilation.assets 是一个键值对,键为需要输出的文件名称,值为文件对应的内容。

compilation.chunks:Compilation中由chunks组成的数组(构建输出)。 每个chunk管理最终渲染资源的组合。

原理简介

  • compilation.hooks.additionalAssets 钩子派发通知的时候,从 compilation.assets(键名是输出资源文件名) 对象里找到键名包含后缀 .css 的
  • 从要处理的文件路径中,过滤出不包含 styleExtensions ( [‘.css’, ‘.scss’, ‘.styl’, ‘.sass’, ‘.less’])数组中后缀的文件路径
  • 从上面过滤完的路径,读文件,content.match(/[A-Za-z0-9_-]+/g),正则匹配出包含这些的字段,存到 set 里。
  • 将 css 解析成 ast,遍历 ast 节点,如果节点的选择器名不在 set 里,就被移除

补充

1.1 Array.from

语法

1
Array.from(arrayLike[, mapFn[, thisArg]])

参数

  • arrayLike

    想要转换成数组的伪数组对象或可迭代对象。

  • mapFn 可选

    如果指定了该参数,新数组中的每个元素会执行该回调函数。

  • thisArg 可选

    可选参数,执行回调函数 mapFnthis 对象。

返回值

一个新的数组实例。

1.2 Generator.prototype.return()

return() 方法返回给定的值并结束生成器。

1.3 Object.getOwnPropertyDescriptors()

Object.getOwnPropertyDescriptors() 方法用来获取一个对象的所有自身属性的描述符。

WX20200225-141518@2x

1.4 Object.defineProperties()

方法直接在一个对象上定义新的属性或修改现有属性,并返回该对象。

1
2
3
4
5
6
7
8
9
10
11
var obj = {};
Object.defineProperties(obj, {
'property1': {
value: true,
writable: true
},
'property2': {
value: 'Hello',
writable: false
}
});