-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
415 lines (362 loc) · 11.1 KB
/
index.ts
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
import webpack from 'webpack';
import path from 'path';
import { validate } from 'schema-utils';
import svgstore from 'svgstore';
import extend from 'extend';
import templatePreview from './preview.js';
import unTypedSchemaOptions from './schemas/plugin-options.json' assert { type: 'json' };
import type { Compiler, Compilation, NormalModule, Chunk, Module, sources } from 'webpack';
import { Schema } from 'schema-utils/declarations/validate.js';
import {
Svgs,
SpriteManifest,
Sprite,
EntryCache,
SvgsData,
PluginOptions,
SvgstoreConfig
} from './types.js';
import { PACKAGE_NAME, esmResolve } from './utils.js';
const schemaOptions = unTypedSchemaOptions as Schema;
/**
* @param {string|number} a First id
* @param {string|number} b Second id
* @returns {-1|0|1} Compare result
*/
const compareIds = (a: string | number, b: string | number) => {
if (typeof a !== typeof b) {
return typeof a < typeof b ? -1 : 1;
}
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
class SvgChunkWebpackPlugin {
options: {
filename: string;
svgstoreConfig: SvgstoreConfig;
generateSpritesManifest: boolean;
generateSpritesPreview: boolean;
};
// This need to find plugin from loader context
PLUGIN_NAME = PACKAGE_NAME;
/**
* Instanciate the constructor
* @param {options}
*/
constructor(options = {}) {
const DEFAULTS: PluginOptions = {
filename: '[name].svg',
svgstoreConfig: {
cleanDefs: false,
cleanSymbols: false,
inline: true
},
generateSpritesManifest: false,
generateSpritesPreview: false
};
this.options = extend(true, DEFAULTS, options);
validate(schemaOptions, this.options, {
name: 'SvgChunkWebpackPlugin',
baseDataPath: 'options'
});
this.hookCallback = this.hookCallback.bind(this);
}
/**
* Apply function is automatically called by the Webpack main compiler
* @param {Compiler} compiler The Webpack compiler variable
*/
apply(compiler: Compiler): void {
compiler.hooks.thisCompilation.tap('SvgChunkWebpackPlugin', this.hookCallback);
}
/**
* Hook expose by the Webpack compiler
* @async
* @param {Compilation} compilation The Webpack compilation variable
*/
async hookCallback(compilation: Compilation): Promise<void> {
// PROCESS_ASSETS_STAGE_ADDITIONAL: Add additional assets to the compilation
compilation.hooks.processAssets.tapPromise(
{
name: 'SvgChunkWebpackPlugin',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
},
this.addAssets.bind(this, compilation)
);
}
/**
* Add assets
* The hook is triggered by webpack
* @async
* @param {Compilation} compilation Webpack compilation
* @returns {Promise<void>}
*/
async addAssets(compilation: Compilation): Promise<void> {
// For better compatibility with future webpack versions
const RawSource = compilation.compiler.webpack.sources.RawSource;
const cache = compilation.getCache('SvgChunkWebpackPlugin');
const entryNames = compilation.entrypoints.keys();
const sprites: Sprite[] = [];
const spritesManifest: SpriteManifest = {};
await Promise.all(
Array.from(entryNames).map(async (entryName: string) => {
const svgsDependencies = this.getSvgsDependenciesByEntrypoint({
compilation,
entryName
});
// For empty chunks
if (!svgsDependencies.length) {
return;
}
const eTag = svgsDependencies
.map((item) => cache.getLazyHashedEtag(item.originalSource() as sources.Source))
.reduce((result, item) => cache.mergeEtags(result, item));
const cacheItem = cache.getItemCache(entryName, eTag);
let output: EntryCache = await cacheItem.getPromise();
if (!output) {
const svgsData = this.getSvgsData({ compilation, svgsDependencies });
const sprite = this.generateSprite(svgsData.svgs);
const source = new RawSource(sprite, false);
output = {
source,
sprite,
filename: this.getFilename({ compilation, entryName, sprite }),
svgPaths: svgsData.svgPaths,
svgNames: svgsData.svgNames
};
await cacheItem.storePromise(output);
}
compilation.emitAsset(output.filename, output.source);
sprites.push({
entryName,
source: output.source,
sprite: output.sprite,
svgs: output.svgNames
});
spritesManifest[entryName] = output.svgPaths;
})
);
if (!sprites.length) {
return;
}
// Need to sort (**always**), to have deterministic build
const eTag = sprites
.sort((a, b) => a.entryName.localeCompare(b.entryName))
.map((item) => cache.getLazyHashedEtag(item.source))
.reduce((result, item) => cache.mergeEtags(result, item));
if (this.options.generateSpritesManifest) {
await this.createSpritesManifest({ compilation, cache, eTag, spritesManifest });
}
if (this.options.generateSpritesPreview) {
await this.createSpritesPreview({ compilation, cache, eTag, sprites });
}
}
/**
* Get SVGs filtered by entrypoints
* @param {Object} options
* @param {Compilation} options.compilation Webpack compilation
* @param {String} options.entryName Entrypoint name
* @returns {NormalModule[]} Svgs list
*/
getSvgsDependenciesByEntrypoint({
compilation,
entryName
}: {
compilation: Compilation;
entryName: string;
}): NormalModule[] {
const listSvgsDependencies: NormalModule[] = [];
// When you use module federation you can don't have entries
const entries = compilation.entrypoints;
if (!entries || entries.size === 0) {
return [];
}
const entry = entries.get(entryName);
if (!entry) {
return [];
}
entry.chunks.forEach((chunk: Chunk) => {
const modules = compilation.chunkGraph.getOrderedChunkModulesIterable(
chunk,
(a: Module, b: Module) =>
compareIds(
a.readableIdentifier(compilation.requestShortener),
b.readableIdentifier(compilation.requestShortener)
)
);
for (const module of modules) {
if (module.buildInfo && module.buildInfo.SVG_CHUNK_WEBPACK_PLUGIN) {
listSvgsDependencies.push(module as NormalModule);
// Mark module as not side effect free after processing in graph
if (module.buildMeta) {
module.buildMeta.sideEffectFree = false;
}
}
}
});
return listSvgsDependencies;
}
/**
* Get SVG data
* @param {Compilation} options
* @param {Compilation} options.compilation Webpack compilation
* @param {String} options.entryName Entrypoint name
* @returns {SvgsData} SVG data (paths, names and content)
*/
getSvgsData({
compilation,
svgsDependencies
}: {
compilation: Compilation;
svgsDependencies: NormalModule[];
}): SvgsData {
const svgPaths: SvgsData['svgPaths'] = [];
const svgNames: SvgsData['svgNames'] = [];
const svgs: SvgsData['svgs'] = [];
svgsDependencies.forEach((normalModule: NormalModule) => {
const { userRequest } = normalModule;
const source = normalModule.originalSource();
if (source) {
svgPaths.push(path.relative(compilation.options.context || '', userRequest));
svgNames.push(path.basename(userRequest, '.svg'));
svgs.push({
name: path.basename(userRequest, '.svg'),
content: JSON.parse(source.source().toString())
});
}
});
return {
svgPaths,
svgNames,
svgs
};
}
/**
* Generate the SVG sprite with Svgstore
* @param {Svgs[]} svgs SVGs list
* @returns {String} Sprite string
*/
generateSprite(svgs: Svgs[]): string {
const sprites = svgstore(this.options.svgstoreConfig);
svgs.forEach((svg: Svgs) => {
sprites.add(svg.name, svg.content);
});
return sprites.toString();
}
/**
* Get the filename for the asset compilation
* Placeholder [name], [hash], [chunkhash], [content] are automatically replaced
* @param {Object} options
* @param {Compilation} options.compilation Webpack compilation
* @param {String} options.entryName Entrypoint name
* @param {String} options.sprite Sprite content
* @returns {String} Sprite filename
*/
getFilename({
compilation,
entryName,
sprite
}: {
compilation: Compilation;
entryName: string;
sprite: string;
}): string {
let filename = this.options.filename;
// Check if the filename option contains the placeholder [name]
// [name] corresponds to the entrypoint name
if (/\[name\]/i.test(filename)) {
filename = filename.replace('[name]', entryName);
}
// Check if the filename option contains the placeholder [fullhash]
// [fullhash] corresponds to the Webpack compilation hash
if (/\[fullhash\]/i.test(filename)) {
const { hashDigestLength } = compilation.outputOptions;
const hash = compilation.fullHash
? compilation.fullHash.substring(0, hashDigestLength)
: '';
filename = filename.replace('[fullhash]', hash);
}
// Check if the filename option contains the placeholder [contenthash]
// [contenthash] corresponds to the sprite content hash
if (/\[contenthash\]/i.test(filename)) {
const { util } = compilation.compiler.webpack;
const { hashFunction, hashDigest, hashDigestLength } = compilation.outputOptions;
let hash = '';
if (hashFunction) {
hash = util
.createHash(hashFunction)
.update(sprite)
.digest(hashDigest)
// @ts-ignore
.substring(0, hashDigestLength);
}
filename = filename.replace('[contenthash]', hash);
}
return filename;
}
/**
* Create sprite manifest with Webpack compilation
* Expose the manifest file into the assets compilation
* The file is automatically created by the compiler
* @async
* @param {Object} options
* @param {Compilation} options.compilation Webpack compilation
* @param {any} options.cache Webpack cache
* @param {any} options.eTag Webpack eTag
* @param {SpriteManifest} options.spritesManifest ETag
* @returns {String} Sprite filename
*/
async createSpritesManifest({
compilation,
cache,
eTag,
spritesManifest
}: {
compilation: Compilation;
cache: any;
eTag: any;
spritesManifest: SpriteManifest;
}): Promise<void> {
const RawSource = compilation.compiler.webpack.sources.RawSource;
const cacheItem = cache.getItemCache('sprites-manifest.json', eTag);
let output: sources.RawSource = await cacheItem.getPromise();
if (!output) {
output = new RawSource(JSON.stringify(spritesManifest, null, 2), false);
await cacheItem.storePromise(output);
}
compilation.emitAsset('sprites-manifest.json', output);
}
/**
* Create sprites preview
* @async
* @param {Object} options
* @param {Compilation} options.compilation Webpack compilation
* @param {any} options.cache Webpack cache
* @param {any} options.eTag Webpack eTag
* @param {Sprite[]} options.sprites Sprites
* @returns {String} Sprite filename
*/
async createSpritesPreview({
compilation,
cache,
eTag,
sprites
}: {
compilation: Compilation;
cache: any;
eTag: any;
sprites: Sprite[];
}): Promise<void> {
const RawSource = compilation.compiler.webpack.sources.RawSource;
const cacheItem = cache.getItemCache('sprites-preview.html', eTag);
let output: sources.RawSource = await cacheItem.getPromise();
if (!output) {
output = new RawSource(templatePreview(sprites), false);
await cacheItem.storePromise(output);
}
compilation.emitAsset('sprites-preview.html', output);
}
}
// @ts-ignore
SvgChunkWebpackPlugin.loader = esmResolve('./loader.js');
export default SvgChunkWebpackPlugin;