-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathwebpack-sprite-hash-plugin.js
More file actions
100 lines (88 loc) · 3.39 KB
/
webpack-sprite-hash-plugin.js
File metadata and controls
100 lines (88 loc) · 3.39 KB
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
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const ALLOWED_RETURN_FORMATS = ['json', 'php']
/**
* Webpack plugin to generate content hashes for SVG sprite files.
* Creates a sprite-hashes.json (or sprite-hashes.asset.php) file in the dist folder.
*
* @param {Object} options Plugin options.
* @param {string} [options.returnFormat='json'] Output format: 'json' or 'php'.
* When 'php', generates a .asset.php file (outputFilename .json → .asset.php).
* @param {string} [options.outputPath='dist'] Output directory.
* @param {string} [options.spritePath='dist/icons'] Sprite SVG directory.
* @param {string} [options.outputFilename='sprite-hashes.json'] Output file name.
* @param {number} [options.hashLength=8] Hash length in characters.
*/
class SpriteHashPlugin {
constructor(options = {}) {
const returnFormat = options.returnFormat || 'json'
if (!ALLOWED_RETURN_FORMATS.includes(returnFormat)) {
throw new Error(`SpriteHashPlugin: returnFormat must be one of ${ALLOWED_RETURN_FORMATS.join(', ')}`)
}
this.options = {
outputPath: options.outputPath || 'dist',
spritePath: options.spritePath || 'dist/icons',
outputFilename: options.outputFilename || 'sprite-hashes.' + returnFormat,
hashLength: options.hashLength || 8,
returnFormat,
}
}
/**
* Formats a plain object as a PHP associative array string.
*
* @param {Record<string, string>} obj Key-value pairs.
* @return {string} PHP array literal.
*/
formatPhpArray(obj) {
const entries = Object.entries(obj).map(([key, value]) => {
const escapedKey = key.replace(/'/g, "\\'")
const escapedValue = String(value).replace(/'/g, "\\'")
return `\t'${escapedKey}' => '${escapedValue}'`
})
return `array(\n${entries.join(',\n')}\n)`
}
apply(compiler) {
compiler.hooks.afterEmit.tapAsync('SpriteHashPlugin', (compilation, callback) => {
const spriteDir = path.resolve(compiler.options.context, this.options.spritePath)
const outputFilename =
this.options.returnFormat === 'php'
? this.options.outputFilename.replace(/\.json$/i, '.asset.php')
: this.options.outputFilename
const outputFile = path.resolve(compiler.options.context, this.options.outputPath, outputFilename)
if (!fs.existsSync(spriteDir)) {
console.warn(`SpriteHashPlugin: Sprite directory not found: ${spriteDir}`)
callback()
return
}
const hashes = {}
const files = fs.readdirSync(spriteDir).filter((file) => file.endsWith('.svg'))
files.forEach((file) => {
const filePath = path.join(spriteDir, file)
const content = fs.readFileSync(filePath)
const hash = crypto.createHash('md5').update(content).digest('hex').substring(0, this.options.hashLength)
// Store with relative path as key
const relativePath = `icons/${file}`
hashes[relativePath] = hash
})
if (this.options.returnFormat === 'php') {
const phpLines = [
'<?php',
'/**',
' * Sprite file hashes. Generated by SpriteHashPlugin.',
' *',
' * @return array<string, string> Path => hash.',
' */',
'return ' + this.formatPhpArray(hashes) + ';',
'',
]
fs.writeFileSync(outputFile, phpLines.join('\n'))
} else {
fs.writeFileSync(outputFile, JSON.stringify(hashes, null, 2))
}
console.log(`SpriteHashPlugin: Generated ${outputFilename} with ${Object.keys(hashes).length} sprites`)
callback()
})
}
}
module.exports = SpriteHashPlugin