|
| 1 | +const simulateRemoteData = key => { |
| 2 | + const data = { |
| 3 | + header: "<div>HEADER</div>", |
| 4 | + footer: "<div>FOOTER</div>", |
| 5 | + }; |
| 6 | + return Promise.resolve(data[key]); |
| 7 | +}; |
| 8 | + |
| 9 | +class StaticPageSlice { |
| 10 | + constructor(options) { |
| 11 | + this.options = options || {}; // 传递参数 |
| 12 | + } |
| 13 | + apply(compiler) { |
| 14 | + compiler.hooks.thisCompilation.tap("StaticPageSlice", compilation => { |
| 15 | + compilation.hooks.processAssets.tapPromise( |
| 16 | + { |
| 17 | + name: "StaticPageSlice", |
| 18 | + stage: compilation.constructor.PROCESS_ASSETS_STAGE_ADDITIONS, |
| 19 | + additionalAssets: true, |
| 20 | + }, |
| 21 | + assets => this.replaceAssets(assets, compilation) |
| 22 | + ); |
| 23 | + }); |
| 24 | + } |
| 25 | + |
| 26 | + replaceAssets(assets, compilation) { |
| 27 | + return new Promise(resolve => { |
| 28 | + const cache = {}; |
| 29 | + const assetKeys = Object.keys(assets); |
| 30 | + for (const key of assetKeys) { |
| 31 | + const isLastAsset = key === assetKeys[assetKeys.length - 1]; |
| 32 | + if (!/.*\.html$/.test(key)) { |
| 33 | + if (isLastAsset) resolve(); |
| 34 | + continue; |
| 35 | + } |
| 36 | + let target = assets[key].source(); |
| 37 | + const matchedValues = target.matchAll(/<!-- inject:name="(\S*?)" -->/g); // `matchAll`函数需要`Node v12.0.0`以上 |
| 38 | + const tags = []; |
| 39 | + for (const item of matchedValues) { |
| 40 | + const [tag, name] = item; |
| 41 | + tags.push({ |
| 42 | + tag, |
| 43 | + name, |
| 44 | + data: cache[name] ? cache[name] : simulateRemoteData(name), |
| 45 | + }); |
| 46 | + } |
| 47 | + Promise.all(tags.map(item => item.data)) |
| 48 | + .then(res => { |
| 49 | + res.forEach((data, index) => { |
| 50 | + const tag = tags[index].tag; |
| 51 | + const name = tags[index].name; |
| 52 | + if (!cache[name]) cache[name] = data; |
| 53 | + target = target.replace(tag, data); |
| 54 | + }); |
| 55 | + }) |
| 56 | + .then(() => { |
| 57 | + compilation.assets[key] = { |
| 58 | + source() { |
| 59 | + return target; |
| 60 | + }, |
| 61 | + size() { |
| 62 | + return this.source().length; |
| 63 | + }, |
| 64 | + }; |
| 65 | + }) |
| 66 | + .then(() => { |
| 67 | + if (isLastAsset) resolve(); |
| 68 | + }); |
| 69 | + } |
| 70 | + }); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +module.exports = StaticPageSlice; |
0 commit comments