|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/*! |
| 4 | + * V4Fire Client Core |
| 5 | + * https://github.com/V4Fire/Client |
| 6 | + * |
| 7 | + * Released under the MIT license |
| 8 | + * https://github.com/V4Fire/Client/blob/master/LICENSE |
| 9 | + */ |
| 10 | + |
| 11 | +const fs = require('fs'); |
| 12 | +const path = require('path'); |
| 13 | +const RuntimeModule = require('webpack/lib/RuntimeModule'); |
| 14 | +const RuntimeGlobals = require('webpack/lib/RuntimeGlobals'); |
| 15 | + |
| 16 | +const {webpack} = require('@config/config'); |
| 17 | + |
| 18 | +class AsyncPlugRuntimeModule extends RuntimeModule { |
| 19 | + constructor() { |
| 20 | + super('async chunk loader for fat-html', RuntimeModule.STAGE_ATTACH); |
| 21 | + } |
| 22 | + |
| 23 | + generate() { |
| 24 | + return `const loadScript = ${RuntimeGlobals.loadScript}; |
| 25 | +${RuntimeGlobals.loadScript} = (path, cb, chunk, id) => { |
| 26 | + const tpl = document.getElementById(id); |
| 27 | + if (tpl?.content) { |
| 28 | + document.body.appendChild(tpl.content.cloneNode(true)); |
| 29 | + cb(); |
| 30 | + } else { |
| 31 | + loadScript(path, cb, chunk, id); |
| 32 | + } |
| 33 | +}`; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +class Index { |
| 38 | + apply(compiler) { |
| 39 | + compiler.hooks.thisCompilation.tap( |
| 40 | + 'AsyncChunksPlugin', |
| 41 | + (compilation) => { |
| 42 | + const onceForChunkSet = new WeakSet(); |
| 43 | + |
| 44 | + compilation.hooks.runtimeRequirementInTree |
| 45 | + .for(RuntimeGlobals.ensureChunkHandlers) |
| 46 | + .tap('AsyncChunksPlugin', (chunk, set) => { |
| 47 | + if (onceForChunkSet.has(chunk)) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + onceForChunkSet.add(chunk); |
| 52 | + |
| 53 | + const runtimeModule = new AsyncPlugRuntimeModule(); |
| 54 | + set.add(RuntimeGlobals.loadScript); |
| 55 | + compilation.addRuntimeModule(chunk, runtimeModule); |
| 56 | + }); |
| 57 | + } |
| 58 | + ); |
| 59 | + |
| 60 | + compiler.hooks.emit.tapAsync('AsyncChunksPlugin', (compilation, callback) => { |
| 61 | + const asyncChunks = []; |
| 62 | + if (compilation.name !== 'runtime') { |
| 63 | + callback(); |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + compilation.chunks.forEach((chunk) => { |
| 68 | + if (chunk.canBeInitial()) { |
| 69 | + return; |
| 70 | + } |
| 71 | + |
| 72 | + asyncChunks.push({ |
| 73 | + id: chunk.id, |
| 74 | + files: chunk.files.map((filename) => filename) |
| 75 | + }); |
| 76 | + }); |
| 77 | + |
| 78 | + const outputPath = path.join(compiler.options.output.path, webpack.asyncAssetsJSON()); |
| 79 | + |
| 80 | + fs.writeFile(outputPath, JSON.stringify(asyncChunks, null, 2), (err) => { |
| 81 | + if (err) { |
| 82 | + compilation.errors.push(new Error(`Error write async chunks list to ${outputPath}`)); |
| 83 | + } |
| 84 | + |
| 85 | + callback(); |
| 86 | + }); |
| 87 | + }); |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +module.exports = Index; |
0 commit comments