|
| 1 | +import { promises as fs } from 'node:fs'; |
| 2 | +import path from 'node:path'; |
| 3 | + |
| 4 | +/** |
| 5 | + * @returns {import('vite').Plugin} |
| 6 | + */ |
| 7 | +export function preloadPlugin() { |
| 8 | + return { |
| 9 | + name: 'preload-plugin', |
| 10 | + async closeBundle() { |
| 11 | + const [manifestContent, replContent, assetsDir] = await Promise.all([ |
| 12 | + fs.readFile(path.resolve('build', '.vite/manifest.json'), 'utf-8'), |
| 13 | + fs.readFile(path.resolve('build', 'repl/index.html'), 'utf-8'), |
| 14 | + fs.readdir(path.resolve('build', 'assets')) |
| 15 | + ]); |
| 16 | + |
| 17 | + const replWorker = `assets/${assetsDir.find((file) => file.startsWith('repl.worker-'))}`; |
| 18 | + |
| 19 | + const manifest = JSON.parse(manifestContent); |
| 20 | + |
| 21 | + let errorOverlay = ''; |
| 22 | + for (const file in manifest) { |
| 23 | + if (manifest[file].name == 'error-overlay') { |
| 24 | + errorOverlay = file; |
| 25 | + break; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + const preloadTags = [ |
| 30 | + 'src/components/controllers/repl-page.jsx', |
| 31 | + 'src/components/controllers/repl/runner.jsx', |
| 32 | + 'src/components/code-editor/index.jsx', |
| 33 | + errorOverlay, |
| 34 | + replWorker |
| 35 | + ].map((file) => { |
| 36 | + const filePath = manifest[file] ? manifest[file].file : file; |
| 37 | + return `\n\t\t<link rel="modulepreload" href="/${filePath}"></link>`; |
| 38 | + }).join(''); |
| 39 | + |
| 40 | + const replWithPreload = replContent.replace( |
| 41 | + '</script>', |
| 42 | + `</script>${preloadTags}` |
| 43 | + ); |
| 44 | + |
| 45 | + await fs.writeFile(path.resolve('build', 'repl/index.html'), replWithPreload); |
| 46 | + } |
| 47 | + }; |
| 48 | +} |
0 commit comments