-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
190 lines (169 loc) · 5.75 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
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
const fs = require('fs')
const path = require('path')
const log = require('debug')('fontmin-webpack')
const _ = require('lodash')
const ttf2woff2 = require('ttf2woff2')
const Fontmin = require('fontmin')
const RawSource = require('webpack-sources').RawSource
const FONT_REGEX = /\.(eot|ttf|svg|woff|woff2)$/
const TEXT_REGEX = /\.(js|css|html)$/
const GLYPH_REGEX = /content\s*:[^};]*?('|")(.*?)\s*('|"|;)/g
const UNICODE_REGEX = /\\(\w{4})/
const FONTMIN_EXTENSIONS = ['eot', 'woff', 'svg']
class FontminPlugin {
constructor(options) {
this._options = _.assign({
glyphs: [],
autodetect: true,
}, options)
}
computeFinalGlyphs(foundGlyphs) {
let glyphs = _.clone(this._options.glyphs)
if (this._options.autodetect) {
glyphs = glyphs.concat(foundGlyphs)
}
return glyphs
}
hasFontAsset(assets) {
return _.find(assets, (val, key) => FONT_REGEX.test(key))
}
findFontFiles(compilation) {
const regular = this.findRegularFontFiles(compilation)
const extract = this.findExtractTextFontFiles(compilation)
return _.uniqBy(regular.concat(extract), 'asset')
}
findRegularFontFiles(compilation) {
return _(compilation.modules)
.filter(module => this.hasFontAsset(module.buildInfo.assets))
.map(module => {
const filename = Array.from(module.buildInfo.fileDependencies)[0]
const font = path.basename(filename, path.extname(filename))
return _.keys(module.buildInfo.assets).map(asset => {
const buffer = module.buildInfo.assets[asset].source()
const extension = path.extname(asset)
return {asset, extension, font, buffer}
})
})
.flatten()
.value()
}
findExtractTextFontFiles(compilation) {
const fileDependencies = _(compilation.modules)
.map(module => Array.from(module.buildInfo.fileDependencies || new Set()))
.flatten()
.filter(filename => FONT_REGEX.test(filename))
.map(filename => {
return {
filename,
stats: fs.statSync(filename),
}
})
.value()
return _(compilation.assets)
.keys()
.filter(name => FONT_REGEX.test(name))
.map(asset => {
const buffer = compilation.assets[asset].source()
const extension = path.extname(asset)
const dependency = fileDependencies.find(dependency => {
return path.extname(dependency.filename) === extension &&
buffer.length === dependency.stats.size
})
const filename = (dependency && dependency.filename) || asset
const font = path.basename(filename, extension)
return {asset, extension, font, buffer}
})
.value()
}
findUnicodeGlyphs(compilation) {
return _(compilation.assets)
.map((asset, name) => ({asset, name}))
.filter(item => TEXT_REGEX.test(item.name))
.map(item => {
const content = item.asset.source()
const matches = content.match(GLYPH_REGEX) || []
return matches
.map(match => {
const unicodeMatch = match.match(UNICODE_REGEX)
return unicodeMatch ?
String.fromCharCode(parseInt(unicodeMatch[1], 16)) :
false
})
.filter(Boolean)
})
.flatten()
.value()
}
setupFontmin(extensions, usedGlyphs = []) {
usedGlyphs = _.isArray(usedGlyphs) ? usedGlyphs : [usedGlyphs]
let fontmin = new Fontmin().use(Fontmin.glyph({text: usedGlyphs.join(' ')}))
FONTMIN_EXTENSIONS.forEach(ext => {
if (extensions.includes('.' + ext)) {
fontmin = fontmin.use(Fontmin[`ttf2${ext}`]())
}
})
return fontmin
}
mergeAssetsAndFiles(group, files) {
const byExtension = _.keyBy(files, 'extname')
return group
.map(item => {
const isWoff2 = item.extension === '.woff2'
const extension = isWoff2 ? '.ttf' : item.extension
const buffer = byExtension[extension] && byExtension[extension].contents
if (!buffer) {
return undefined
}
const minified = isWoff2 ? ttf2woff2(buffer) : buffer
return _.assign(item, {minified})
})
.filter(Boolean)
}
minifyFontGroup(group, usedGlyphs = []) {
log('analyzing font group:', _.get(group, '0.font'))
const ttfInfo = _.find(group, {extension: '.ttf'})
if (!ttfInfo) {
log('font group has no TTF file, skipping...')
return Promise.resolve([])
}
const extensions = _.map(group, 'extension')
const fontmin = this.setupFontmin(extensions, usedGlyphs)
return new Promise((resolve, reject) => {
fontmin
.src(ttfInfo.buffer)
.run((err, files) => {
if (err) {
reject(err)
} else {
resolve(this.mergeAssetsAndFiles(group, files))
}
})
})
}
onAdditionalAssets(compilation, done) {
const fontFiles = this.findFontFiles(compilation)
const glyphsInCss = this.findUnicodeGlyphs(compilation)
log(`found ${glyphsInCss.length} glyphs in CSS`)
const minifiableFonts = _(fontFiles).groupBy('font').values()
const glyphs = this.computeFinalGlyphs(glyphsInCss)
minifiableFonts.reduce((prev, group) => {
return prev
.then(() => this.minifyFontGroup(group, glyphs))
.then(files => {
files.forEach(file => {
if (file.buffer.length > file.minified.length) {
compilation.assets[file.asset] = new RawSource(file.minified)
}
})
})
}, Promise.resolve()).then(done).catch(done)
}
apply(compiler) {
compiler.hooks.thisCompilation.tap('FontminPlugin', compilation => {
compilation.hooks.additionalAssets.tapAsync('FontminPlugin', done => {
this.onAdditionalAssets(compilation, done)
})
})
}
}
module.exports = FontminPlugin