1 | import fs from 'fs';
|
2 | import path from 'path';
|
3 | import RequestShortener from 'webpack/lib/RequestShortener';
|
4 |
|
5 | function ExtractAssets(modules, requestShortener, publicPath) {
|
6 | var emitted = false;
|
7 | var assets = modules
|
8 | .map(m => {
|
9 | var assets = Object.keys(m.assets || {});
|
10 |
|
11 | if (assets.length === 0) {
|
12 | return undefined;
|
13 | }
|
14 |
|
15 | var asset = assets[0];
|
16 | emitted = emitted || m.assets[asset].emitted;
|
17 |
|
18 | return {
|
19 | name: m.readableIdentifier(requestShortener),
|
20 | asset: asset
|
21 | };
|
22 | }).filter(m => {
|
23 | return m !== undefined;
|
24 | }).reduce((acc, m) => {
|
25 | acc[m.name] = path.join(publicPath, m.asset);
|
26 | return acc;
|
27 | }, {});
|
28 |
|
29 | return [emitted, assets];
|
30 | }
|
31 |
|
32 | function ExtractChunks(chunks, publicPath) {
|
33 | var emitted = false;
|
34 | var chunks = chunks
|
35 | .map(c => {
|
36 | return {
|
37 | name: c.name,
|
38 | files: c.files
|
39 | .filter(f => path.extname(f) !== '.map')
|
40 | .map(f => path.join(publicPath, f))
|
41 | };
|
42 | })
|
43 | .reduce((acc, c) => {
|
44 | acc[c.name] = c.files;
|
45 | return acc;
|
46 | }, {});
|
47 |
|
48 | return [emitted, chunks];
|
49 | }
|
50 |
|
51 | export default class AssetMapPlugin {
|
52 | |
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | constructor(outputFile, relativeTo) {
|
59 | this.outputFile = outputFile;
|
60 | this.relativeTo = relativeTo;
|
61 | }
|
62 |
|
63 | apply(compiler) {
|
64 | compiler.plugin('done', stats => {
|
65 | var publicPath = stats.compilation.outputOptions.publicPath;
|
66 | var requestShortener = new RequestShortener(this.relativeTo || path.dirname(this.outputFile));
|
67 |
|
68 | var [assetsEmitted, assets] = ExtractAssets(stats.compilation.modules, requestShortener, publicPath);
|
69 | var [chunksEmitted, chunks] = ExtractChunks(stats.compilation.chunks, publicPath);
|
70 |
|
71 | if (assetsEmitted || chunksEmitted) {
|
72 | fs.writeFileSync(this.outputFile, JSON.stringify({ assets, chunks }));
|
73 | }
|
74 | });
|
75 | }
|
76 | }
|