/
index.js
74 lines (71 loc) · 1.96 KB
/
index.js
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
const path = require('path')
const UglifyJS = require('uglify-es')
const handleStaticResource = (dist, match, compilation) => {
const hits = Object.keys(compilation.assets).filter(key => {
return match.test(path.join(dist, key))
})
hits.forEach(hit => {
let content = compilation.assets[hit].source()
if (content instanceof Buffer) {
content = content.toString('utf8')
}
const result = UglifyJS.minify(content, {
mangle: {
toplevel: true
}
})
if (!result.error) {
compilation.assets[hit] = {
source() {
return result.code
},
size() {
return result.code.length
}
}
}
})
}
class UglifyStaticJSWebpackPlugin {
constructor(options = {}) {
if ('staticPaths' in options) {
if (!Array.isArray(options.staticPaths)) {
throw new Error(
'[UglifyStaticJSWebpackPlugin Error]: staticPaths parameter type must be Array'
)
}
this.options = options
} else {
this.options = null
}
}
apply(compiler) {
console.log('\n===UglifyStaticJSWebpackPlugin===')
if (this.options) {
const dirs = this.options['staticPaths']
const dist = compiler.options.output.path
let regStr = ''
regStr = dirs
.map((d, i) => {
if (!path.isAbsolute(d)) {
d = path.join(dist, d)
}
return '^{word}\\b'.replace('{word}', d)
})
.join('|')
const match = new RegExp(`^${regStr}\\b`, 'gi')
if (compiler.hooks) {
compiler.hooks.emit.tap('UglifyStaticJSWebpackPlugin', compilation => {
handleStaticResource(dist, match, compilation)
})
} else {
compiler.plugin('emit', (compilation, callback) => {
handleStaticResource(dist, match, compilation)
callback()
})
}
}
console.log('\n===/UglifyStaticJSWebpackPlugin===')
}
}
module.exports = UglifyStaticJSWebpackPlugin