/
index.js
142 lines (119 loc) · 3.63 KB
/
index.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
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
const rsort = require('route-sort');
const NAME = 'webpack-route-manifest';
function toAsset(str) {
if (/\.js$/i.test(str)) return 'script';
if (/\.(svg|jpe?g|png|webp)$/i.test(str)) return 'image';
if (/\.(woff2?|otf|ttf|eot)$/i.test(str)) return 'font';
if (/\.css$/i.test(str)) return 'style';
return false;
}
function toLink(assets, _pattern, _filemap) {
let value = '';
assets.forEach(obj => {
if (value) value += ', ';
value += `<${obj.href}>; rel=preload; as=${obj.type}`;
if (/^(font|script)$/.test(obj.type)) value += '; crossorigin=anonymous';
});
return [{ key: 'Link', value }];
}
function toFunction(val) {
if (typeof val === 'function') return val;
if (typeof val === 'object') return key => val[key];
}
class RouteManifest {
constructor(opts={}) {
const { routes, assets, headers, minify } = opts;
const { filename='manifest.json', sort=true, inline=true } = opts;
if (!routes) {
throw new Error('A "routes" mapping is required');
}
const toRoute = toFunction(routes);
const toHeaders = toFunction(headers) || headers === true && toLink;
const toType = toFunction(assets) || toAsset;
this.run = bundle => {
const Pages = new Map();
const Manifest = {};
const Files = {};
const { publicPath, chunks, modules } = bundle.getStats().toJson();
// Map pages to files
chunks.forEach(chunk => {
const { id, files, origins, entry } = chunk;
const origin = origins[0].request;
const route = origin && !entry ? toRoute(origin) : '*';
if (route) {
Pages.set(id, {
assets: new Set(files),
pattern: route
});
}
});
// Grab extra files per route
modules.forEach(mod => {
mod.assets.forEach(asset => {
mod.chunks.forEach(id => {
const tmp = Pages.get(id);
if (tmp) {
tmp.assets.add(asset);
Pages.set(id, tmp);
}
});
});
});
// Construct `Files` first
Pages.forEach(obj => {
let tmp = Files[obj.pattern] = Files[obj.pattern] || [];
// Iterate, possibly filtering out
// TODO: Add priority hints?
obj.assets.forEach(str => {
let type = toType(str);
let href = publicPath + str;
if (type) tmp.push({ type, href });
});
});
function write(data) {
// Get the 1st script that's globally shared
const asset = Files['*'].find(x => x.type === 'script');
const script = asset && asset.href && asset.href.replace(publicPath, '');
if (inline && script && bundle.assets[script]) {
let nxt = `window.__rmanifest=${JSON.stringify(data)};`;
nxt += bundle.assets[script].source();
// TODO: Does NOT invalidate hash
// ~> bcuz too late in the chain
bundle.assets[script] = {
size: () => nxt.length,
source: () => nxt
};
}
const str = JSON.stringify(data, null, minify ? 0 : 2);
bundle.assets[filename] = {
size: () => str.length,
source: () => str
};
}
// All patterns
const routes = Object.keys(Files);
if (sort) rsort(routes);
// No headers? Then stop here
if (!toHeaders) {
if (!sort) return write(Files); // order didn't matter
return write(routes.reduce((o, key) => (o[key]=Files[key], o), {}));
}
// Otherwise compute "headers" per pattern
// And save existing Files as "files" key
routes.forEach(pattern => {
const files = Files[pattern];
const headers = toHeaders(files, pattern, Files) || [];
Manifest[pattern] = { files, headers };
});
return write(Manifest);
};
}
apply(compiler) {
if (compiler.hooks !== void 0) {
compiler.hooks.emit.tap(NAME, this.run);
} else {
compiler.plugin('emit', this.run);
}
}
}
module.exports = RouteManifest;