Repository navigation
fix: wait for a chunk's css on every dynamic import #320
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
DylanPiercey
wants to merge
1
commit into
main
Choose a base branch
from
dpiercey-ws-agent-feedback-wejtdz
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@marko/vite": patch | ||
| --- | ||
|
|
||
| Make every dynamic import of a chunk wait for its stylesheets, so a lazily loaded template imported again while its CSS is still loading no longer renders unstyled. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| import assert from "assert"; | ||
| import fs from "fs"; | ||
| import os from "os"; | ||
| import path from "path"; | ||
| import type * as viteNamespace from "vite"; | ||
| import vm from "vm"; | ||
|
|
||
| import preloadCssPlugin, { patchPreloadHelper } from "../preload-css"; | ||
|
|
||
| const preloadHelperId = "\0vite/preload-helper.js"; | ||
|
|
||
| // Runs Vite's preload helper against a stub DOM where each stylesheet link | ||
| // loads (or fails) only when the test says so. | ||
| function loadHelper(code: string) { | ||
| const links: FakeLink[] = []; | ||
| class FakeLink extends EventTarget { | ||
| rel = ""; | ||
| as = ""; | ||
| href = ""; | ||
| crossOrigin = ""; | ||
| setAttribute() {} | ||
| } | ||
| const context = vm.createContext({ | ||
| __VITE_IS_MODERN__: true, | ||
| __importMeta: { | ||
| url: "http://localhost/assets/main.js", | ||
| resolve: (specifier: string) => | ||
| new URL(specifier, "http://localhost/").href, | ||
| }, | ||
| document: { | ||
| getElementsByTagName: () => links, | ||
| querySelector: () => null, | ||
| createElement: () => new FakeLink(), | ||
| head: { appendChild: (link: FakeLink) => links.push(link) }, | ||
| }, | ||
| window: new EventTarget(), | ||
| Event, | ||
| EventTarget, | ||
| Promise, | ||
| URL, | ||
| Error, | ||
| }); | ||
| vm.runInContext( | ||
| code | ||
| .replace("export const __vitePreload", "globalThis.__vitePreload") | ||
| .replaceAll("import.meta", "__importMeta"), | ||
| context, | ||
| ); | ||
| const preload = context.__vitePreload as ( | ||
| load: () => Promise<unknown>, | ||
| deps: string[], | ||
| ) => Promise<unknown>; | ||
| const importChunk = () => { | ||
| const state = { settled: false as false | "resolved" | "rejected" }; | ||
| preload(() => Promise.resolve("chunk"), ["assets/lazy.css"]).then( | ||
| () => (state.settled = "resolved"), | ||
| () => (state.settled = "rejected"), | ||
| ); | ||
| return state; | ||
| }; | ||
| return { links, importChunk }; | ||
| } | ||
|
|
||
| const flush = () => new Promise((resolve) => setImmediate(resolve)); | ||
|
|
||
| describe("preload css", () => { | ||
| let vite: typeof viteNamespace; | ||
| let dir: string; | ||
| let helper: string; | ||
|
|
||
| before(async () => { | ||
| vite = await import("vite"); | ||
| dir = fs.mkdtempSync(path.join(os.tmpdir(), "marko-vite-preload-")); | ||
| fs.writeFileSync( | ||
| path.join(dir, "index.html"), | ||
| `<script type="module" src="./main.js"></script>`, | ||
| ); | ||
| fs.writeFileSync(path.join(dir, "main.js"), `import("./lazy.js");`); | ||
| fs.writeFileSync(path.join(dir, "lazy.js"), `import "./lazy.css";`); | ||
| fs.writeFileSync(path.join(dir, "lazy.css"), `.lazy { color: teal }`); | ||
| await vite.build({ | ||
| root: dir, | ||
| logLevel: "silent", | ||
| build: { write: false }, | ||
| plugins: [ | ||
| { | ||
| name: "capture-preload-helper", | ||
| transform: { | ||
| filter: { id: /^\0vite\/preload-helper\.js$/ }, | ||
| handler(code, id) { | ||
| if (id === preloadHelperId) helper = code; | ||
| }, | ||
| }, | ||
| }, | ||
| ], | ||
| }); | ||
| }); | ||
|
|
||
| after(() => fs.rmSync(dir, { recursive: true, force: true })); | ||
|
|
||
| it("patches the helper in a build", async () => { | ||
| const output = (await vite.build({ | ||
| root: dir, | ||
| logLevel: "silent", | ||
| build: { write: false, minify: false }, | ||
| plugins: [preloadCssPlugin()], | ||
| })) as viteNamespace.Rolldown.RolldownOutput; | ||
| assert.ok( | ||
| output.output.some( | ||
| (chunk) => | ||
| chunk.type === "chunk" && chunk.code.includes("__markoCssLoad"), | ||
| ), | ||
| ); | ||
| }); | ||
|
|
||
| it("makes every import wait for a stylesheet still loading", async () => { | ||
| const { links, importChunk } = loadHelper(patchPreloadHelper(helper)!); | ||
| const first = importChunk(); | ||
| const second = importChunk(); | ||
| await flush(); | ||
| assert.deepEqual([first.settled, second.settled], [false, false]); | ||
|
|
||
| links[0].dispatchEvent(new Event("load")); | ||
| await flush(); | ||
| assert.deepEqual([first.settled, second.settled], ["resolved", "resolved"]); | ||
| const later = importChunk(); | ||
| await flush(); | ||
| assert.equal(later.settled, "resolved"); | ||
| }); | ||
|
|
||
| it("fails every import waiting on a stylesheet that fails", async () => { | ||
| const { links, importChunk } = loadHelper(patchPreloadHelper(helper)!); | ||
| const first = importChunk(); | ||
| const second = importChunk(); | ||
| links[0].dispatchEvent(new Event("error")); | ||
| await flush(); | ||
| assert.deepEqual([first.settled, second.settled], ["rejected", "rejected"]); | ||
| }); | ||
|
|
||
| it("leaves a helper it does not recognize alone", () => { | ||
| assert.equal( | ||
| patchPreloadHelper("export const __vitePreload = 1"), | ||
| undefined, | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import type * as vite from "vite"; | ||
|
|
||
| const preloadHelperReg = /^\0vite\/preload-helper\.js$/; | ||
| const seenCheckReg = | ||
| /if\s*\(dep in seen\)\s*return;?\s*seen\[dep\]\s*=\s*true;?/; | ||
| const appendLinkReg = /document\.head\.appendChild\(link\);?/; | ||
|
|
||
| /** | ||
| * Vite's preload helper only makes the dynamic import that inserts a | ||
| * stylesheet wait for it to load. Another import needing that stylesheet while | ||
| * it loads (eg a lazy template imported again) resolves early and renders | ||
| * unstyled, so the pending load is shared with every caller until it settles. | ||
| */ | ||
| export default function preloadCssPlugin(): vite.Plugin { | ||
| return { | ||
| name: "marko-vite:preload-css", | ||
| apply: "build", | ||
| transform: { | ||
| filter: { id: preloadHelperReg }, | ||
| handler(code) { | ||
| return patchPreloadHelper(code); | ||
| }, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the helper with shared stylesheet loads, or `undefined` when its | ||
| * code no longer has the shape this patches (eg Vite fixed it upstream). | ||
| */ | ||
| export function patchPreloadHelper(code: string): string | undefined { | ||
| if (!seenCheckReg.test(code) || !appendLinkReg.test(code)) return; | ||
| return ( | ||
| code | ||
| .replace( | ||
| seenCheckReg, | ||
| "if (dep in seen) return seen[dep];\nseen[dep] = void 0;", | ||
| ) | ||
| .replace( | ||
| appendLinkReg, | ||
| "$&\nif (isCss) seen[dep] = __markoCssLoad(link, dep, seen);", | ||
| ) + | ||
| ` | ||
| function __markoCssLoad(link, dep, seen) { | ||
| const loaded = new Promise((res, rej) => { | ||
| link.addEventListener("load", res); | ||
| link.addEventListener("error", () => rej(new Error(\`Unable to preload CSS for \${dep}\`))); | ||
| }); | ||
| const settle = () => { seen[dep] = void 0; }; | ||
| loaded.then(settle, settle); | ||
| return loaded; | ||
| } | ||
| ` | ||
| ); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Also require the injected identifier
isCssbefore patching.The inserted statement reads
isCss. The guard on Line 32 checks onlyseenCheckRegandappendLinkReg. If a future Vite 8 minor release renames or inlinesisCssbut keeps both anchors, the plugin still patches the helper. Every dynamic import with a CSS dependency then throwsReferenceError: isCss is not defined. That breaks the promise that an unexpected helper shape stays untouched. The peer rangevite: ^8allows such minor releases. The build test only covers the Vite version installed in this repo.Use the helper's existing
if (isCss) { return new Promise(...) }block afterappendChild(link)as the anchor. Replace that block with the shared load. The guard then also checksisCss, and each link gets one pair of listeners instead of two.Proposed fix
.replace( appendLinkReg, - "$&\nif (isCss) seen[dep] = __markoCssLoad(link, dep, seen);", + "document.head.appendChild(link);\nif (isCss) return (seen[dep] = __markoCssLoad(link, dep, seen));\nif (isCss) { return new Promise(", ) +Also applies to: 32-32, 39-42
🤖 Prompt for AI Agents