Skip to content

Commit 1bf0ddd

Browse files
authoredJan 15, 2024
Add fallback compile for astro script and style load (#9664)
1 parent d38b2a4 commit 1bf0ddd

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed
 

‎.changeset/friendly-needles-invite.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"astro": patch
3+
---
4+
5+
Improves HMR for Astro style and script modules

‎packages/astro/src/vite-plugin-astro/index.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ interface AstroPluginOptions {
2727
export default function astro({ settings, logger }: AstroPluginOptions): vite.Plugin[] {
2828
const { config } = settings;
2929
let resolvedConfig: vite.ResolvedConfig;
30+
let server: vite.ViteDevServer;
3031

3132
// Variables for determining if an id starts with /src...
3233
const srcRootWeb = config.srcDir.pathname.slice(config.root.pathname.length - 1);
@@ -38,6 +39,9 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl
3839
configResolved(_resolvedConfig) {
3940
resolvedConfig = _resolvedConfig;
4041
},
42+
configureServer(_server) {
43+
server = _server;
44+
},
4145
async load(id, opts) {
4246
const parsedId = parseAstroRequest(id);
4347
const query = parsedId.query;
@@ -46,9 +50,18 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl
4650
}
4751
// For CSS / hoisted scripts, the main Astro module should already be cached
4852
const filename = normalizePath(normalizeFilename(parsedId.filename, config.root));
49-
const compileResult = getCachedCompileResult(config, filename);
53+
let compileResult = getCachedCompileResult(config, filename);
5054
if (!compileResult) {
51-
return null;
55+
// In dev, HMR could cause this compile result to be empty, try to load it first
56+
if (server) {
57+
await server.transformRequest('/@fs' + filename);
58+
compileResult = getCachedCompileResult(config, filename);
59+
}
60+
61+
// If there's really no compilation result, error
62+
if (!compileResult) {
63+
throw new Error('No cached compile result found for ' + id);
64+
}
5265
}
5366

5467
switch (query.type) {

0 commit comments

Comments
 (0)
Please sign in to comment.