-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathsprite-hash-plugin.js
More file actions
73 lines (64 loc) · 1.78 KB
/
sprite-hash-plugin.js
File metadata and controls
73 lines (64 loc) · 1.78 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
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.json file in the dist folder.
*/
class SpriteHashPlugin {
constructor(options = {}) {
this.options = {
outputPath: options.outputPath || 'dist',
spritePath: options.spritePath || 'dist/icons',
outputFilename: options.outputFilename || 'sprite-hashes.json',
hashLength: options.hashLength || 8,
};
}
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;
});
fs.writeFileSync(outputFile, JSON.stringify(hashes, null, 2));
console.log(
`SpriteHashPlugin: Generated ${
this.options.outputFilename
} with ${Object.keys(hashes).length} sprites`
);
callback();
}
);
}
}
module.exports = SpriteHashPlugin;