Unverified Commit e6ad5cf8 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

fix(turbopack): give eager `import.meta.glob` values the ESM namespace (#96559)

Eager glob values were built with a plain CommonJS require, so the value
was a
module's `exports` object rather than its ESM namespace — for JSON (or
any
CommonJS) module that meant no CommonJS interop ran, so
`modules[path].default`
(the shape our own docs show) and `{ import: 'default' }` were
`undefined`. A
hand-written `import * as ns from './data.json'` did have `default`.

Eager values now use the same namespace-import primitive a static
`import * as ns from '…'` produces.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 32af7900
...@@ -846,8 +846,9 @@ impl EcmascriptChunkPlaceable for ImportMetaGlobAsset { ...@@ -846,8 +846,9 @@ impl EcmascriptChunkPlaceable for ImportMetaGlobAsset {
// Generate the value expression based on eager/lazy and import options // Generate the value expression based on eager/lazy and import options
let value_expr = if this.eager { let value_expr = if this.eager {
// Eager: direct synchronous require // Eager: synchronously evaluate the module and use its ESM namespace,
let module_expr = pm.create_require(Cow::Borrowed(&key_expr)); // matching what a static `import * as ns from "..."` would produce.
let module_expr = pm.create_esm_require(Cow::Borrowed(&key_expr));
// If `import` option is set, access the named export // If `import` option is set, access the named export
if let Some(named) = &this.import { if let Some(named) = &this.import {
quote!( quote!(
......
...@@ -141,6 +141,34 @@ impl SinglePatternMapping { ...@@ -141,6 +141,34 @@ impl SinglePatternMapping {
} }
} }
/// Like [`Self::create_require`], but evaluates to the ESM *namespace* of the
/// module instead of its CommonJS `exports` object, so that the CommonJS
/// interop applies. This is what a static `import * as ns from "..."`
/// produces, and it is the difference between a JSON (or CommonJS) module
/// having a `default` export and not having one.
pub fn create_esm_require(&self, key_expr: Cow<'_, Expr>) -> Expr {
match self {
Self::Invalid => self.create_id(key_expr),
Self::Unresolvable(request) => throw_module_not_found_expr(request),
Self::Ignored => quote!("{}" as Expr),
Self::Dropped => quote!("0" as Expr),
Self::Module(_) | Self::ModuleLoader(_) => quote!(
"$turbopack_import($arg)" as Expr,
turbopack_import: Expr = TURBOPACK_IMPORT.into(),
arg: Expr = self.create_id(key_expr)
),
Self::External(request, ExternalType::CommonJs) => quote!(
"$turbopack_external_require($arg, () => require($arg), true)" as Expr,
turbopack_external_require: Expr = TURBOPACK_EXTERNAL_REQUIRE.into(),
arg: Expr = request.as_str().into()
),
Self::External(request, ty) => throw_module_not_found_error_expr(
request,
&format!("Unsupported external type {ty:?} for esm reference"),
),
}
}
pub fn create_import(&self, key_expr: Cow<'_, Expr>, import_externals: bool) -> Expr { pub fn create_import(&self, key_expr: Cow<'_, Expr>, import_externals: bool) -> Expr {
match self { match self {
Self::Invalid => { Self::Invalid => {
......
// An eager `import.meta.glob` must produce the same module namespace a
// hand-written `import * as ns from '...'` produces, including the `default`
// export that the CommonJS interop adds for JSON and CommonJS modules.
import * as jsonNamespace from './data/data.json'
import * as cjsNamespace from './data/cjs.js'
const eager = import.meta.glob('./data/*', { eager: true })
it('should expose the default export of a JSON module', () => {
expect(Object.keys(eager)).toEqual([
'./data/cjs.js',
'./data/data.json',
'./data/esm.mjs',
])
expect(eager['./data/data.json'].default).toEqual({ hello: 'world' })
})
it('should match a hand-written namespace import for JSON', () => {
expect(jsonNamespace.default).toEqual({ hello: 'world' })
expect({ ...eager['./data/data.json'] }).toEqual({ ...jsonNamespace })
})
it('should match a hand-written namespace import for CommonJS', () => {
expect(eager['./data/cjs.js'].default).toEqual({ hello: 'cjs' })
expect({ ...eager['./data/cjs.js'] }).toEqual({ ...cjsNamespace })
})
it('should keep working for ES modules', () => {
expect(eager['./data/esm.mjs'].default).toBe('esm')
expect(eager['./data/esm.mjs'].value).toBe(7)
})
const eagerDefault = import.meta.glob('./data/*', {
eager: true,
import: 'default',
})
it('should support import: "default" eagerly', () => {
expect(eagerDefault['./data/data.json']).toEqual({ hello: 'world' })
expect(eagerDefault['./data/cjs.js']).toEqual({ hello: 'cjs' })
expect(eagerDefault['./data/esm.mjs']).toBe('esm')
})
const lazy = import.meta.glob('./data/*')
it('should expose the default export of a JSON module lazily', async () => {
const mod = await lazy['./data/data.json']()
expect(mod.default).toEqual({ hello: 'world' })
})
const lazyDefault = import.meta.glob('./data/*', { import: 'default' })
it('should support import: "default" lazily', async () => {
expect(await lazyDefault['./data/data.json']()).toEqual({ hello: 'world' })
expect(await lazyDefault['./data/esm.mjs']()).toBe('esm')
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment