-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.ts
239 lines (206 loc) · 5.66 KB
/
index.ts
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import type { Plugin, ResolvedConfig } from 'vite'
import type { CompressionOptions, VitePluginCompression } from './types'
import path from 'path'
import { normalizePath } from 'vite'
import { readAllFile, isRegExp, isFunction } from './utils'
import fs from 'fs-extra'
import chalk from 'chalk'
import zlib from 'zlib'
import Debug from 'debug'
const debug = Debug.debug('vite-plugin-compression')
const extRE = /\.(js|mjs|json|css|html)$/i
const mtimeCache = new Map<string, number>()
export default function (options: VitePluginCompression = {}): Plugin {
let outputPath: string
let config: ResolvedConfig
const emptyPlugin: Plugin = {
name: 'vite:compression',
}
const {
disable = false,
filter = extRE,
verbose = true,
threshold = 1025,
compressionOptions = {},
deleteOriginFile = false,
// eslint-disable-next-line
success = () => {},
} = options
let { ext = '' } = options
const { algorithm = 'gzip' } = options
if (algorithm === 'gzip' && !ext) {
ext = '.gz'
}
if (algorithm === 'brotliCompress' && !ext) {
ext = '.br'
}
if (disable) {
return emptyPlugin
}
debug('plugin options:', options)
return {
...emptyPlugin,
apply: 'build',
enforce: 'post',
configResolved(resolvedConfig) {
config = resolvedConfig
outputPath = path.isAbsolute(config.build.outDir)
? config.build.outDir
: path.join(config.root, config.build.outDir)
debug('resolvedConfig:', resolvedConfig)
},
async closeBundle() {
let files = readAllFile(outputPath) || []
debug('files:', files)
if (!files.length) return
files = filterFiles(files, filter)
const compressOptions = getCompressionOptions(
algorithm,
compressionOptions,
)
const compressMap = new Map<
string,
{ size: number; oldSize: number; cname: string }
>()
const handles = files.map(async (filePath: string) => {
const { mtimeMs, size: oldSize } = await fs.stat(filePath)
if (mtimeMs <= (mtimeCache.get(filePath) || 0) || oldSize < threshold)
return
let content = await fs.readFile(filePath)
if (deleteOriginFile) {
fs.remove(filePath)
}
try {
content = await compress(content, algorithm, compressOptions)
} catch (error) {
config.logger.error('compress error:' + filePath)
}
const size = content.byteLength
const cname = getOutputFileName(filePath, ext)
compressMap.set(filePath, {
size: size / 1024,
oldSize: oldSize / 1024,
cname: cname,
})
await fs.writeFile(cname, content)
mtimeCache.set(filePath, Date.now())
})
return Promise.all(handles).then(() => {
if (verbose) {
handleOutputLogger(config, compressMap, algorithm)
success()
}
})
},
}
}
function filterFiles(
files: string[],
filter: RegExp | ((file: string) => boolean),
) {
if (filter) {
const isRe = isRegExp(filter)
const isFn = isFunction(filter)
files = files.filter((file) => {
if (isRe) {
return (filter as RegExp).test(file)
}
if (isFn) {
// eslint-disable-next-line
return (filter as Function)(file)
}
return true
})
}
return files
}
/**
* get common options
*/
function getCompressionOptions(
algorithm = '',
compressionOptions: CompressionOptions = {},
) {
const defaultOptions: {
[key: string]: Record<string, any>
} = {
gzip: {
level: zlib.constants.Z_BEST_COMPRESSION,
},
deflate: {
level: zlib.constants.Z_BEST_COMPRESSION,
},
deflateRaw: {
level: zlib.constants.Z_BEST_COMPRESSION,
},
brotliCompress: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]:
zlib.constants.BROTLI_MAX_QUALITY,
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
},
},
}
return {
...defaultOptions[algorithm],
...compressionOptions,
} as CompressionOptions
}
/**
* Compression core method
* @param content
* @param algorithm
* @param options
*/
function compress(
content: Buffer,
algorithm: 'gzip' | 'brotliCompress' | 'deflate' | 'deflateRaw',
options: CompressionOptions = {},
) {
return new Promise<Buffer>((resolve, reject) => {
// @ts-ignore
zlib[algorithm](content, options, (err, result) =>
err ? reject(err) : resolve(result),
)
})
}
/**
* Get the suffix
* @param filepath
* @param ext
*/
function getOutputFileName(filepath: string, ext: string) {
const compressExt = ext.startsWith('.') ? ext : `.${ext}`
return `${filepath}${compressExt}`
}
// Packed output logic
function handleOutputLogger(
config: ResolvedConfig,
compressMap: Map<string, { size: number; oldSize: number; cname: string }>,
algorithm: string,
) {
config.logger.info(
`\n${chalk.cyan('✨ [vite-plugin-compression]:algorithm=' + algorithm)}` +
` - compressed file successfully: `,
)
const keyLengths = Array.from(compressMap.keys(), (name) => name.length)
const maxKeyLength = Math.max(...keyLengths)
compressMap.forEach((value, name) => {
const { size, oldSize, cname } = value
const rName = normalizePath(cname).replace(
normalizePath(`${config.build.outDir}/`),
'',
)
const sizeStr = `${oldSize.toFixed(2)}kb / ${algorithm}: ${size.toFixed(
2,
)}kb`
config.logger.info(
chalk.dim(path.basename(config.build.outDir) + '/') +
chalk.blueBright(rName) +
' '.repeat(2 + maxKeyLength - name.length) +
' ' +
chalk.dim(sizeStr),
)
})
config.logger.info('\n')
}