UNPKG

1.47 kBJavaScriptView Raw
1/* @flow */
2
3/**
4 * Creates a mapper that maps components used during a server-side render
5 * to async chunk files in the client-side build, so that we can inline them
6 * directly in the rendered HTML to avoid waterfall requests.
7 */
8
9import type { ClientManifest } from './index'
10
11export type AsyncFileMapper = (files: Array<string>) => Array<string>;
12
13export function createMapper (
14 clientManifest: ClientManifest
15): AsyncFileMapper {
16 const map = createMap(clientManifest)
17 // map server-side moduleIds to client-side files
18 return function mapper (moduleIds: Array<string>): Array<string> {
19 const res = new Set()
20 for (let i = 0; i < moduleIds.length; i++) {
21 const mapped = map.get(moduleIds[i])
22 if (mapped) {
23 for (let j = 0; j < mapped.length; j++) {
24 res.add(mapped[j])
25 }
26 }
27 }
28 return Array.from(res)
29 }
30}
31
32function createMap (clientManifest) {
33 const map = new Map()
34 Object.keys(clientManifest.modules).forEach(id => {
35 map.set(id, mapIdToFile(id, clientManifest))
36 })
37 return map
38}
39
40function mapIdToFile (id, clientManifest) {
41 const files = []
42 const fileIndices = clientManifest.modules[id]
43 if (fileIndices) {
44 fileIndices.forEach(index => {
45 const file = clientManifest.all[index]
46 // only include async files or non-js assets
47 if (clientManifest.async.indexOf(file) > -1 || !(/\.js($|\?)/.test(file))) {
48 files.push(file)
49 }
50 })
51 }
52 return files
53}