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