Repository navigation
fix(vite): scan top-level imports with Vite's native parser - #11634
aleclarson wants to merge 2 commits into
Conversation
Babel's skipBlockComment rescans to the next line break for every block comment, so a module whose code sits on a few very long lines parses quadratically. A large served dependency (about 2,000 block comments on a 1.9 MB line) took ~1.5 s per Babel parse, and the /ns/m pipeline parsed it about six times per request while blocking the dev server event loop. iOS loader requests then timed out during cold boot. Top-level import record collection and the dev default-import link check now use Vite's parseAst (Oxc) and fall back to the previous Babel parse when Oxc rejects the input.
|
View your CI Pipeline Execution ↗ for commit 619ee10
💡 With Ultracache enabled, Nx Cloud learns each task's file inputs in CI and uses them on later runs. Turn on Ultracache in workspace settings ↗ · Read docs ↗ ☁️ Nx Cloud last updated this comment at |
commit: |
NathanWalker
left a comment
There was a problem hiding this comment.
Thanks, the pathological case is real and this fixes it. I checked parity carefully since start/end are used to splice served code: across 37 probe cases (astral chars/BOM/hashbang/CRLF/U+2028 before imports, import type and inline type specifiers, import attributes, TLA, import.meta, dynamic import(), export */export {} from, side-effect imports, import-like text in strings/comments, decorators, Vue SFC output, TS generics/JSX ambiguities), records are identical wherever both parsers succeed, and importKind: 'type' still reaches isTypeOnly. A differential run (Babel alongside Oxc in parseTopLevelStatements) over the whole vite suite showed no mismatches. Where they disagree, Oxc accepts some code Babel rejected (now rewritten instead of passed through, harmless for Vite output) and the <!-- case falls back to Babel.
Verified: vite suite 1975 passed on the head, 1977 merged with main; tsc and prettier clean.
Approving; the main thing worth doing (here or in a follow-up) is perf, inline. Other nits inline. Open questions:
hasEsmDefaultExport,astExtractImportsAndStripTypes,collectReExportAndDynamicImportSourcesand the Babel parses inwebsocket-module-bindings.tsstill hit the same Babel slowdown. Follow-up planned?import defer/import sourcenow parse, and the clause regex inwebsocket-module-bindings.tswould readdefer * as ns/source wasmas a normal clause. Vite doesn't emit them today, but skipping them explicitly would be safer.
| */ | ||
| export function parseTopLevelStatements(code: string): any[] | null { | ||
| try { | ||
| const ast = parseAst(code, { lang: 'tsx' }) as any; |
There was a problem hiding this comment.
Perf: parseAst deserializes the whole ESTree into JS objects, which on normally formatted code is slower than the Babel parse it replaces. Measured on ~290 real .mjs files from node_modules (total per bucket):
| size | files | Babel | parseAst |
parseSync().module |
|---|---|---|---|---|
| <50 KB | 222 | 107 ms | 122 ms | 34 ms |
| 50–300 KB | 54 | 225 ms | 328 ms | 68 ms |
| >300 KB | 14 | 477 ms | 695 ms | 121 ms |
These scans run ~6–8× per /ns/m request, so typical apps with large deps get slower while the pathological case gets faster.
parseSync('f.tsx', code, { lang: 'tsx' }) (also exported from vite) never materializes the AST: check .errors, read .module.staticImports. It has UTF-16 offsets, the statement span, moduleRequest.value, and per-entry importName.kind (Default/Name/NamespaceObject) with spans; declaration-level type-only can be derived from every entry's isType (or ^import\s+type\b). 3–4× faster than Babel across sizes, and 1.8 ms vs 6.4 ms for parseAst on the pathological input. (Only confirmed exported in 8.0.2.)
| import * as path from 'path'; | ||
| import { parseAst } from 'vite'; | ||
|
|
||
| const babelTraverse: any = (traverse as any)?.default || (traverse as any); |
There was a problem hiding this comment.
Nit: the Babel fallback is repeated in three places (here, in collectStaticImportDefaultIntents, and in websocket-module-bindings.ts), and this fallback does a full @babel/traverse even though a top-level scan is equivalent. If parseTopLevelStatements owned the Babel fallback and returned body | null, all three callers become simple filters and this import goes away. (Also, this const sits between import groups.)
| it('parses a long minified line full of block comments without Babel quadratic scan', () => { | ||
| // Babel's skipBlockComment rescans to the next line break per comment; | ||
| // 12000 comments over a ~20MB single line is ~10s through the old path. | ||
| // Measured on this machine: Babel 10.32s, Oxc 0.047s. |
There was a problem hiding this comment.
Nit: machine-specific timings belong in the PR description rather than the source (tools/notes/CodeComments.md). Also, the wall-clock < 2s assertions on 20 MB+ inputs are fine today (~0.05 s) but timing-based; asserting the Oxc path was taken would be sturdier. Small gaps: the import type test only checks source, not that bindings still see isTypeOnly === true; and a few imports sit mid-file (:48, :49, :116, and a mid-file await import in websocket-import-records-fallback.spec.ts:42).
What
The
/ns/mdev route parses each served module with Babel several times just to find its top-level imports (collectTopLevelImportRecordsin two places, plus the dev default-import link check). On modules whose code sits on a few very long lines, Babel'sskipBlockCommentbecomes quadratic: for every block comment it runslineBreakG.test(this.input)from the comment start to the next line break anywhere in the input, not just to the comment's end.Real case: a 3.9 MB dependency chunk (
shaders/dist/core/std-*.js) is transformed by Vite's dev pipeline into 225 lines, the longest 1.9 MB with about 2,000 block comments. One Babel parse of that output takes ~1.5 s (0.26 s on the original multi-line file), and a single cold request did about six of them. CPU profiles showed@babel/parserat 8.7 s of an 11.25 s request, 7.2 s of it inskipBlockComment. Because this runs synchronously, the dev server's event loop is blocked for the whole request, and the iOS runtime's module loader timed out during cold boot (NSURLErrorDomain -1001) before the app could start.How
parseTopLevelStatements(code)inwebsocket-served-module-helpers.tsreturns top-level statements from Vite'sparseAst(code, { lang: 'tsx' })(Oxc), ornullif Oxc rejects the code.collectTopLevelImportRecordsimplementations use it first and fall back to the unchanged Babel parse. If both fail, they still return[]. Node checks are plaintypecomparisons that work on either AST. Output fields are unchanged.collectStaticImportDefaultIntents(code)replaces the link check's inline parse and traverse. Static imports can only appear at top level, so scanning top-levelImportDeclarations is equivalent. It falls back to the previous Babel parse and traverse, and still throws on a double failure, so the caller'stry/catchbehaves as before.astExtractImportsAndStripTypes,collectReExportAndDynamicImportSources, the normalizer) are untouched.viteis already a dependency of@nativescript/vite(^8.0.0), so no new dependency.Test plan
npx vitest run hmr/server/websocket-served-module-helpers.spec.ts hmr/server/websocket-import-records-fallback.spec.ts: 26 pass. Covers default, named and string-named specifiers, exacttextslices after non-ASCII text,import type, TS+JSX input, no imports, a forced Oxc failure falling back to Babel,ensureNativeScriptModuleBindingson both paths, and default-import intents.npx nx run vite:build. Touched files are lint-clean;vite:lintstill reports 3 existing errors in untouched files (configuration/base.ts,css-device-module.ts).@babel/parsershare dropped from 8.7 s to 1.2 s. A serial cold crawl of the app's 1,443-module boot graph went from 241.6 s to 108.9 s, with the slowest module dropping from 4.9 s to 1.4 s.