|
| 1 | +import MagicString from 'magic-string'; |
| 2 | + |
| 3 | +import type { OutputChunk, Plugin } from 'rollup'; |
| 4 | +import type * as d from '../../../declarations'; |
| 5 | + |
| 6 | +/** |
| 7 | + * A Rollup plugin to generate unique bundle IDs for lazy-loaded modules. |
| 8 | + * @param buildCtx The build context |
| 9 | + * @param config The validated configuration |
| 10 | + * @param shouldHash Whether to hash the bundle ID |
| 11 | + * @param suffix The suffix to append to the bundle ID |
| 12 | + * @returns A Rollup plugin |
| 13 | + */ |
| 14 | +export const lazyBundleIdPlugin = ( |
| 15 | + buildCtx: d.BuildCtx, |
| 16 | + config: d.ValidatedConfig, |
| 17 | + shouldHash: boolean, |
| 18 | + suffix: string, |
| 19 | +): Plugin => { |
| 20 | + const getBundleId = async (entryKey: string, code: string, suffix: string): Promise<string> => { |
| 21 | + if (shouldHash && config.sys?.generateContentHash) { |
| 22 | + const hash = await config.sys.generateContentHash(code, config.hashedFileNameLength); |
| 23 | + return `p-${hash}${suffix}`; |
| 24 | + } |
| 25 | + |
| 26 | + const components = entryKey.split('.'); |
| 27 | + let bundleId = components[0]; |
| 28 | + if (components.length > 2) { |
| 29 | + bundleId = `${bundleId}_${components.length - 1}`; |
| 30 | + } |
| 31 | + |
| 32 | + return bundleId + suffix; |
| 33 | + }; |
| 34 | + |
| 35 | + return { |
| 36 | + name: 'lazyBundleIdPlugin', |
| 37 | + async generateBundle(_, bundle) { |
| 38 | + const files = Object.entries<OutputChunk>(bundle as any); |
| 39 | + const map = new Map<string, string>(); |
| 40 | + |
| 41 | + for (const [_key, file] of files) { |
| 42 | + if (!file.isEntry) continue; |
| 43 | + |
| 44 | + const entryModule = buildCtx.entryModules.find((em) => em.entryKey === file.name); |
| 45 | + if (!entryModule) continue; |
| 46 | + |
| 47 | + map.set(file.fileName, (await getBundleId(file.name, file.code, suffix)) + '.entry.js'); |
| 48 | + } |
| 49 | + |
| 50 | + if (!map.size) return; |
| 51 | + |
| 52 | + for (const [_key, file] of files) { |
| 53 | + if (!file.isEntry) continue; |
| 54 | + |
| 55 | + file.facadeModuleId = map.get(file.fileName) || file.facadeModuleId; |
| 56 | + file.fileName = map.get(file.fileName) || file.fileName; |
| 57 | + |
| 58 | + const magicString = new MagicString(file.code); |
| 59 | + |
| 60 | + file.imports.forEach((imported: string, i) => { |
| 61 | + const replaced = map.get(imported); |
| 62 | + if (replaced) { |
| 63 | + magicString.replaceAll(imported, replaced); |
| 64 | + file.imports[i] = replaced; |
| 65 | + } |
| 66 | + }); |
| 67 | + file.code = magicString.toString(); |
| 68 | + |
| 69 | + if (config.sourceMap) { |
| 70 | + file.map = magicString.generateMap(); |
| 71 | + } |
| 72 | + } |
| 73 | + }, |
| 74 | + }; |
| 75 | +}; |
0 commit comments