|
| 1 | +/* @flow */ |
| 2 | + |
| 3 | +/** |
| 4 | + * Creates a mapper that maps files 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 | + |
| 9 | +export function createMapper (serverStats: Object, clientStats: Object) { |
| 10 | + const fileMap = createFileMap(serverStats, clientStats) |
| 11 | + return function mapFiles (files: Array<string>): Array<string> { |
| 12 | + const res = new Set() |
| 13 | + for (let i = 0; i < files.length; i++) { |
| 14 | + const mapped = fileMap.get(files[i]) |
| 15 | + if (mapped) { |
| 16 | + for (let j = 0; j < mapped.length; j++) { |
| 17 | + res.add(mapped[j]) |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + return Array.from(res) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +function createFileMap (serverStats, clientStats) { |
| 26 | + const fileMap = new Map() |
| 27 | + serverStats.assets |
| 28 | + .filter(asset => /\.js$/.test(asset.name)) |
| 29 | + .forEach(asset => { |
| 30 | + const mapped = mapFile(asset.name, serverStats, clientStats) |
| 31 | + fileMap.set(asset.name, mapped) |
| 32 | + }) |
| 33 | + return fileMap |
| 34 | +} |
| 35 | + |
| 36 | +function mapFile (file, serverStats, clientStats) { |
| 37 | + // 1. server file -> server chunk ids |
| 38 | + const serverChunkIds = new Set() |
| 39 | + const asset = serverStats.assets.find(asset => asset.name === file) |
| 40 | + if (!asset) return [] |
| 41 | + asset.chunks.forEach(id => { |
| 42 | + const chunk = serverStats.chunks.find(c => c.id === id) |
| 43 | + if (!chunk.initial) { // only map async chunks |
| 44 | + serverChunkIds.add(id) |
| 45 | + } |
| 46 | + }) |
| 47 | + |
| 48 | + // 2. server chunk ids -> module identifiers |
| 49 | + const moduleIdentifiers = [] |
| 50 | + serverStats.modules.forEach(module => { |
| 51 | + if (module.chunks.some(id => serverChunkIds.has(id))) { |
| 52 | + moduleIdentifiers.push(module.identifier) |
| 53 | + } |
| 54 | + }) |
| 55 | + |
| 56 | + // 3. module identifiers -> client chunk ids |
| 57 | + const clientChunkIds = new Set() |
| 58 | + moduleIdentifiers.forEach(identifier => { |
| 59 | + const clientModule = clientStats.modules.find(m => m.identifier === identifier) |
| 60 | + if (clientModule && clientModule.chunks.length === 1) { // ignore modules duplicated in multiple chunks |
| 61 | + clientChunkIds.add(clientModule.chunks[0]) |
| 62 | + } |
| 63 | + }) |
| 64 | + |
| 65 | + // 4. client chunks -> client files |
| 66 | + const clientFiles = new Set() |
| 67 | + Array.from(clientChunkIds).forEach(id => { |
| 68 | + const chunk = clientStats.chunks.find(chunk => chunk.id === id) |
| 69 | + if (!chunk.initial) { |
| 70 | + chunk.files.forEach(file => clientFiles.add(file)) |
| 71 | + } |
| 72 | + }) |
| 73 | + |
| 74 | + return Array.from(clientFiles) |
| 75 | +} |
0 commit comments