-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathwebpack-sprite-hash-plugin.js
More file actions
94 lines (83 loc) · 2.92 KB
/
webpack-sprite-hash-plugin.js
File metadata and controls
94 lines (83 loc) · 2.92 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
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
/**
* Webpack plugin to generate content hashes for SVG sprite files.
* Creates a sprite-hashes.php file in the dist folder.
*
* @param {Object} options Plugin options.
* @param {string} [options.outputPath='dist'] Output directory.
* @param {string} [options.spritePath='dist/icons'] Sprite SVG directory.
* @param {string} [options.outputFilename='sprite-hashes.php'] Output file name.
* @param {number} [options.hashLength=8] Hash length in characters.
*/
class SpriteHashPlugin {
constructor(options = {}) {
this.options = {
outputPath: options.outputPath || 'dist',
spritePath: options.spritePath || 'dist/icons',
outputFilename: options.outputFilename || 'sprite-hashes.asset.php',
hashLength: options.hashLength || 8,
}
}
/**
* Escapes a string for safe use inside a PHP single-quoted string literal.
*
* @param {string} str Input string.
* @return {string} Escaped string.
*/
_escapePhpSingleQuoted(str) {
return String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'")
}
/**
* 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 = this._escapePhpSingleQuoted(key)
const escapedValue = this._escapePhpSingleQuoted(value)
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 outputFile = path.resolve(compiler.options.context, this.options.outputPath, this.options.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
})
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'))
console.log(
`SpriteHashPlugin: Generated ${this.options.outputFilename} with ${Object.keys(hashes).length} sprites`
)
callback()
})
}
}
module.exports = SpriteHashPlugin