forked from theGC/html-webpack-inline-svg-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·524 lines (312 loc) · 12.6 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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
'use strict'
const path = require('path')
const chalk = require('chalk')
const parse5 = require('parse5')
const _ = require('lodash')
const fs = require('fs')
const SVGO = require('svgo')
const svgoDefaultConfig = require(path.resolve(__dirname, 'svgo-config.js'))
/**
* class to inline SVGs within html-webpack-plugin templates
*
*/
class HtmlWebpackInlineSVGPlugin {
constructor (options) {
if (options && options.runPreEmit) {
this.runPreEmit = true
}
this.userConfig = ''
this.outputPath = ''
this.files = []
}
/**
* required to create a webpack plugin
* @param {object} compiler - webpack compiler
*
*/
apply (compiler) {
// Hook into the html-webpack-plugin processing
compiler.plugin('compilation', (compilation) => {
if (this.runPreEmit) {
compilation.plugin('html-webpack-plugin-after-html-processing', (htmlPluginData, callback) => {
// get the custom config
this.getUserConfig(htmlPluginData)
// process the images
return this.processImages(htmlPluginData.html)
.then((html) => {
htmlPluginData.html = html || htmlPluginData.html
return typeof callback === 'function' ?
callback(null, htmlPluginData) :
htmlPluginData
})
.catch((err) => {
console.log(err)
return typeof callback === 'function' ?
callback(null, htmlPluginData) :
htmlPluginData
})
})
} else {
compilation.plugin('html-webpack-plugin-after-emit', (htmlPluginData, callback) => {
// fetch the output path from webpack
this.outputPath = compilation.outputOptions &&
compilation.outputOptions.path ?
compilation.outputOptions.path :
''
if (!this.outputPath) {
console.log(chalk.red('no output path found on compilation.outputOptions'))
return typeof callback === 'function' ?
callback(null, htmlPluginData) :
htmlPluginData
}
// get the custom config
this.getUserConfig(htmlPluginData)
// get the filename
const filename = htmlPluginData.outputName ? htmlPluginData.outputName : ''
if (!filename) {
console.log(chalk.red('no filename found on htmlPluginData.outputName'))
return typeof callback === 'function' ?
callback(null, htmlPluginData) :
htmlPluginData
}
// get the emitted HTML - prior to SVG's being inlined
const originalHtml = htmlPluginData.html.source()
// add filename and original html to the file array
this.files.push({
filename,
originalHtml,
})
// fire callback to pass control to any further plugins
return typeof callback === 'function' ?
callback(null, htmlPluginData) :
htmlPluginData
})
}
})
// hook after-emit so we can read the generated SVG assets within
// the output directory
if (!this.runPreEmit) {
compiler.plugin('after-emit', (compilation, callback) => {
if (!this.files.length) {
console.log(chalk.green('no files passed for SVG inline to process'))
return
}
// iterate over each file and inline it's SVGs
// then return a callback if available
return Promise.all(this.files.map(file => this.processImages(file.originalHtml)))
.then((htmlArray) => Promise.all(htmlArray.map((html, index) => this.updateOutputFile(html, this.files[index].filename))))
.then(() => typeof callback === 'function' ? callback() : null)
.catch((err) => console.log(chalk.red(err.message)))
})
}
}
/**
* get the users custom config
* @param {Object} htmlPluginData
*
*/
getUserConfig (htmlPluginData) {
this.userConfig =
htmlPluginData &&
htmlPluginData.plugin.options &&
_.isObject(htmlPluginData.plugin.options.svgoConfig) ?
htmlPluginData.plugin.options.svgoConfig :
{}
}
/**
* once we've inlined all SVGs and generated the final html
* we need to write it to the file output by html-webpack-plugin
* Note: we can not simply update the callbacks html as we are
* working with the emitted data due to allowing for webpack to first
* resolve and output all files
* @param {string} html - processed and updated html with inlined SVGs
* @param {string} filename - the template file we are currently processing
* @returns {Promise}
*
*/
updateOutputFile (html, filename) {
if (!this.outputPath || !filename) return Promise.reject(new Error('outputPath & filename must be set to update output file'))
else if (!html) return Promise.resolve()
return new Promise((resolve, reject) => {
// set the output file to the updated html
fs.writeFile(path.resolve(this.outputPath, filename), html, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
/**
* find all inline images and replace their html within the output
* @param {string} html - generated html from html-webpack-plugin
* @returns {Promise}
*
*/
processImages (html) {
return new Promise((resolve, reject) => {
const documentFragment = parse5.parseFragment(html, {
locationInfo: true
})
// grab the images to process from the original DOM fragment
const inlineImages = this.getInlineImages(documentFragment)
// if we have no inlined images return the html
if (!inlineImages.length) return resolve()
// process the imageNodes
this.updateHTML(html, inlineImages)
.then((html) => resolve(html))
.catch((err) => {
console.log(chalk.underline.red('processImages hit error'))
console.log(chalk.red(err))
reject(err)
})
})
}
/**
* run the Promises in a synchronous order
* allows us to ensure we have completed processing of an inline image
* before the next ones Promise is called (via then chaining)
* @param {object} html
* @param {array} inlineImages
* @returns {Promise}
*
*/
updateHTML (html, inlineImages) {
return inlineImages.reduce((promise, imageNode) => {
return promise
.then((html) => {
return this.processImage(html)
})
.catch(err => console.log(err))
}, Promise.resolve(html))
}
/**
* get the first inline image and replace it with its inline SVG
* @returns {Promise}
*
*/
processImage (html) {
return new Promise((resolve, reject) => {
// rebuild the document fragment each time with the updated html
const documentFragment = parse5.parseFragment(html, {
locationInfo: true,
})
const inlineImage = this.getFirstInlineImage(documentFragment)
if (inlineImage) {
this.processOutputHtml(html, inlineImage)
.then((html) => {
resolve(html)
})
.catch((err) => reject(err))
} else {
// no inline image - just resolve
resolve(html)
}
})
}
/**
* get a count for how many inline images the html document contains
* @param {Object} documentFragment - parse5 processed html
* @param {array} inlineImages
* @returns {array}
*
*/
getInlineImages (documentFragment, inlineImages) {
if (!inlineImages) inlineImages = []
if (documentFragment.childNodes && documentFragment.childNodes.length) {
documentFragment.childNodes.forEach((childNode) => {
if (this.isNodeValidInlineImage(childNode)) {
inlineImages.push(childNode)
} else {
inlineImages = this.getInlineImages(childNode, inlineImages)
}
})
}
return inlineImages
}
/**
* return the first inline image or false if none
* @param {Object} documentFragment - parse5 processed html
* @returns {null|Object} - null if no inline image - parse5 documentFragment if there is
*
*/
getFirstInlineImage (documentFragment) {
const inlineImages = this.getInlineImages(documentFragment)
if (!inlineImages.length) return null
return inlineImages[0]
}
/**
* check if a node is a valid inline image
* @param {Object} node - parse5 documentFragment
* @returns {boolean}
*
*/
isNodeValidInlineImage (node) {
return !!(
node.nodeName === 'img' &&
_.filter(node.attrs, { name: 'inline' }).length &&
this.getImagesSrc(node))
}
/**
* get an inlined images src
* @param {Object} inlineImage - parse5 document
* @returns {string}
*
*/
getImagesSrc (inlineImage) {
const svgSrcObject = _.find(inlineImage.attrs, { name: 'src' })
// image does not have a src attribute
if (!svgSrcObject) return ''
// grab the image src
const svgSrc = svgSrcObject.value
// image src attribute must not be blank and it must be referencing a file with a .svg extension
return svgSrc && svgSrc.indexOf('.svg') !== -1 ? svgSrc : ''
}
/**
* append the inlineImages SVG data to the output HTML and remove the original img
* @param {string} html
* @param {Object} inlineImage - parse5 document
* @returns {Promise}
*
*/
processOutputHtml (html, inlineImage) {
return new Promise((resolve, reject) => {
const svgSrc = this.getImagesSrc(inlineImage)
// if the image isn't valid resolve
if (!svgSrc) return resolve(html)
// read in the svg
fs.readFile(path.resolve(this.outputPath, svgSrc), 'utf8', (err, data) => {
if (err) reject(err)
const configObj = Object.assign(svgoDefaultConfig, this.userConfig)
const config = {}
// pass all objects to the config.plugins array
config.plugins = _.map(configObj, (value, key) => ({ [key]: value }));
// create a new instance of SVGO
// passing it the merged config, to optimize the svg
const svgo = new SVGO(config)
svgo.optimize(data)
.then((result) => {
const optimisedSVG = result.data
html = this.replaceImageWithSVG(html, inlineImage, optimisedSVG)
resolve(html)
})
.catch((err) => console.log(chalk.red(err.message)))
})
})
}
/**
* replace the img with the optimised SVG
* @param {string} html
* @param {Object} inlineImage - parse5 document
* @param {Object} svg
*
*/
replaceImageWithSVG (html, inlineImage, svg) {
const start = inlineImage.__location.startOffset
const end = inlineImage.__location.endOffset
// remove the img tag and add the svg content
return html.substring(0, start) + svg + html.substring(end)
}
}
module.exports = HtmlWebpackInlineSVGPlugin