next.js
cc65c414 - Turbopack: generate require.context as a synthetic module (#100526)

Commit
25 days ago
Turbopack: generate require.context as a synthetic module (#100526) ## Summary `require.context()` used a hand-written virtual module with its own references and codegen. It is now a synthetic CommonJS source next to the calling module (`<file>.require-context.cjs`) that lists the matched files and `require`s each one. That module goes through normal module handling, so resolution, transforms and chunking all come from the standard paths, and about 270 lines of special-case code go away. The synthetic source has a source map that maps all of its code to the `require.context()` call, so issues located in it (e.g. a match that fails to resolve) are reported at the call. Behaviour changes: - The filter regex is now part of the module ident. Before, two contexts over the same directory with different filters in one file collided. - Matched files are no longer resolved up front, which also removes a second resolution pass done only for static analysis. - Like webpack, every file can also be requested without one of the resolve extensions, and a default file (`index`) as its directory, so `keys()` includes `./dir/file` next to `./dir/file.js`. The filter applies to these keys, and they are sorted. This enables the previously disabled "no regex" case of `test/e2e/app-dir/require-context`, which now gives the same keys with both bundlers. ## Performance This does represent a small performance regression in `require.context` since the synthetic module now goes through the normal module processing path. The cost isn't parsing (there is more, but it wasn't measurable), the cost is due to analysis and reference creation. A pathological benchmark on `import.meta.glob` which is pursuing a similar approach estimated the overhead at 800us per import.meta.glob call. Given how rare these apis are this is acceptable. ## Verification - `test/e2e/app-dir/require-context` (dev and start, Turbopack) - New snapshot test `turbopack-tests/tests/snapshot/imports/require-context`; the new execution test case fails on the old code. <!-- NEXT_JS_LLM --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Author
Parents
Loading