-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.js
72 lines (65 loc) · 2.36 KB
/
plugin.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
const loaderUtils = require('loader-utils');
const svgSpriteState = require('./utils/spriteState');
class SvgSpriteGeneratorPlugin {
constructor(params) {
this.params = params;
}
// eslint-disable-next-line class-methods-use-this
apply(compiler) {
// webpack module instance can be accessed from the compiler object,
// this ensures that correct version of the module is used
// (do not require/import the webpack or any symbols from it directly).
const { webpack } = compiler;
// RawSource is one of the "sources" classes that should be used
// to represent asset sources in compilation.
const { RawSource } = webpack.sources;
compiler.hooks.thisCompilation.tap(
SvgSpriteGeneratorPlugin.name,
(compilation) => {
compilation.hooks.processAssets.tap(
{
name: SvgSpriteGeneratorPlugin.name,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
(assets, callback) => {
if (compilation.options.loader.target === 'web') {
try {
Object.keys(svgSpriteState.sprites).forEach(
(spriteFilePath) => {
const spriteContent = svgSpriteState.getSpriteContent(
spriteFilePath,
this.params
);
const interpolatedPath = loaderUtils.interpolateName(
{ resourcePath: spriteFilePath },
spriteFilePath,
{
context: compilation.options.context,
content: spriteContent,
}
);
if (compilation.getAsset(interpolatedPath)) {
compilation.updateAsset(
interpolatedPath,
new RawSource(spriteContent)
);
} else {
compilation.emitAsset(
interpolatedPath,
new RawSource(spriteContent)
);
}
}
);
} catch (error) {
console.error(error);
callback(error);
}
}
}
);
}
);
}
}
module.exports = SvgSpriteGeneratorPlugin;