Externals are fully parsed during build when resolved through the CommonJS plugin

Aperta
#7 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
43/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Tranquilla
Stack tecnologico
node.js, rollup, typescript
Ambito
build-system

Direzione di ricerca

Start by tracing the node-externals resolution and traceInclude handling described in the issue, including the nested this.resolve() calls that reach the CommonJS plugin. Compare how Node resolution and Rollup plugin resolution affect module loading, while preserving dependency tracing. Done means externals detection no longer loads the full package graph and traceInclude entries remain traceable; the issue provides a reproduction and memory measurements but names no source files or tests.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug externals rollup
Environment

Environment: nitropack 2.13.4 (via Nuxt 4.5.2), rollup 4.62.4, @rollup/plugin-commonjs 29.0.3, Node 24, pnpm 12, node-server preset.

Reproduction
  1. Create a Nitro app with a handler that imports a large ESM package (@maizzle/framework works), and add it to externals.external.
  2. Run the build with NODE_OPTIONS=--max-old-space-size=2048. It runs out of memory during "Building Nitro server".
  3. A Rollup plugin added via the rollup:before hook can log this.getModuleIds() in buildEnd: the package's whole graph is present, with isExternal: false and no importers.
Describe the bug
What happens

A package marked external is still parsed in full, along with everything it imports, even though none of it ends up in the bundle.

To decide whether an import is external, node-externals resolves it with this.resolve(originalId, importer, options). That runs the other plugins' resolveId, including @rollup/plugin-commonjs's. For any id that looks like it could be CommonJS (.js), commonjs calls this.load(resolved) to inspect it. Rollup then resolves that module's imports, each of which goes through node-externals → this.resolve → commonjs → this.load again.

The loaded modules have no importers in the final graph: once node-externals returns external: true, they are dropped. But they are all parsed, transformed and kept in memory until the build ends.

externals.traceInclude entries trigger the same cascade, because buildEnd resolves each one with this.resolve().

Impact

Our server imports @maizzle/framework (an ESM email build tool with a large graph: Vite, Tailwind, PostCSS plugins, oxfmt, cheerio, …), listed in externals.external.

  • Rollup parsed 844 modules (~14 MB of source) for a server bundle whose output is ~3.5 MB. Live heap at the end of bundling was ~2.2 GB.
  • The build needed more than 3 GB of heap. It ran out of memory on GitHub's ubuntu-latest runners, where Node's default heap is ~2 GB (FATAL ERROR: Ineffective mark-compacts near heap limit). It passed locally only because the default heap there is 4 GB.
  • @vercel/nft itself is not the problem: run standalone with the exact same inputs and options Nitro passes, it peaks at ~300 MB.
Evidence that this is avoidable
  • Declaring the package external through Rollup's own external option, which is checked before any plugin resolves the import, dropped the parse to 402 modules / ~5 MB and live heap to ~877 MB. That breaks tracing, though, since node-externals never sees the import.

  • Our current workaround keeps the two entry points away from the CommonJS plugin:

    nitro: {
      commonJS: {
        exclude: [/[\\/]node_modules[\\/](@maizzle[\\/]framework|vue[\\/]compiler-sfc)[\\/]/],
      },
    }
    

    With it, the build passes at 1.5 GB, takes 76 s instead of ~130 s, and .output/server is byte-for-byte identical (same 2,231 files, same sizes, same chunk bytes).

Suggestion

Externals detection shouldn't cause modules to be loaded. A few possible ways:

  • Resolve bare specifiers in node-externals with Node resolution directly (it already uses tryResolve), not this.resolve().
  • Pass a custom flag in the nested this.resolve() that tells the commonjs plugin not to this.load().
  • Resolve traceInclude entries without going through Rollup at all.

Is Nitro v3 affected by the same pattern?

Additional context
Related gaps we hit with the same setup

These all come from shipping a package that runs a build tool at request time. Happy to split any of them into separate issues.

  1. traceInclude silently drops entries that don't resolve. buildEnd does const path = await this.resolve(pkgName); if (path?.id) { … }, so a typo or an unresolvable package produces a build that looks complete but fails at runtime. A warning or error would save a lot of debugging.

  2. traceInclude resolves from the project root. Under pnpm's isolated layout, transitive dependencies (Vite's rolldown, its native binding, lightningcss) can't be reached by bare name from there, so we compute absolute paths ourselves by walking the dependency chain. Documenting that entries must be absolute paths, or resolving them from the package that depends on them, would help.

  3. Native bindings chosen at runtime aren't traced, and only the build machine's variant can be. napi-rs packages (rolldown, lightningcss) load @scope/binding-<platform>-<arch>-<libc> from optionalDependencies at runtime, so nft can't see them, and we add them to traceInclude by hand. Building on Debian (glibc) and running on Alpine (musl) means also detecting libc ourselves and installing the musl packages with pnpm install --libc=musl. A trace target option ({ platform, arch, libc }), or recognizing the napi-rs optionalDependencies pattern, would remove this. nitrojs/nitro#4140 looks related.

  4. CSS can't be included through traceInclude. A .css entry resolves to a virtual \0raw: id, which the tracer then tries to open as a path. We copy the stylesheets into .output/server/node_modules in a compiled hook instead.

  5. import.meta.url is a placeholder while chunks load. In the build, import.meta.url becomes globalThis._importMeta_.url. Chunks initialise it to { url: "file:///_entry.js" }, and index.mjs sets the real value only in its own module body, after its imports have been evaluated. Code that computes a path from import.meta.url at module top level gets the placeholder, with no error. For example, walking up from the module's own directory to find node_modules ends at /. Keeping the native import.meta.url for Node presets, or setting it in a module evaluated first, would avoid that.

Each of these needed a workaround in our build configuration. With them fixed, the externals config alone should be enough to produce a working .output.

Logs

Lingua principale
TypeScript
Stelle
1
Fork
6
Merge medio
1g 2h
PR unite (30g)
20

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

  • Nessun Dockerfile né file Docker Compose
  • Ha un modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di nitrojs/nitro-v2

Tutte le issue di nitrojs/nitro-v2

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.