Skip to content

Commit ba0a42e

Browse files
committed
feat: Try out some simple preloading
1 parent e0cdb1a commit ba0a42e

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

plugins/preload.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

vite.config.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { netlifyPlugin } from './plugins/netlify.js';
99
import { spaFallbackMiddlewarePlugin } from './plugins/spa-fallback-middleware.js';
1010
import { htmlRoutingMiddlewarePlugin } from './plugins/html-routing-middleware.js';
1111
import { rssFeedPlugin } from './plugins/rss-feed.js';
12+
import { preloadPlugin } from './plugins/preload.js';
1213

1314
// TODO: Should we do this for all routes, rely on discovery a bit less?
1415
import { tutorialRoutes } from './src/lib/route-utils.js';
@@ -20,7 +21,9 @@ export default defineConfig({
2021
},
2122
build: {
2223
target: ['chrome88', 'edge88', 'es2020', 'firefox78', 'safari14'],
23-
outDir: 'build'
24+
outDir: 'build',
25+
manifest: true
26+
},
2427
},
2528
plugins: [
2629
replace({
@@ -58,6 +61,7 @@ export default defineConfig({
5861
netlifyPlugin(),
5962
spaFallbackMiddlewarePlugin(),
6063
htmlRoutingMiddlewarePlugin(),
61-
rssFeedPlugin()
64+
rssFeedPlugin(),
65+
preloadPlugin()
6266
]
6367
});

0 commit comments

Comments
 (0)