Unverified Commit 7b848a4e authored by kelvin's avatar kelvin Committed by GitHub

Turbopack: accept a module type argument for import.meta.glob (#96991)

### What?

Adds support for passing a module type to the TypeScript overloads for
`import.meta.glob`:

```ts
const entries = import.meta.glob<Entry>("./entries/*.ts");
```

This works with both lazy and eager imports. If a module type isn’t
provided, it defaults to `unknown`, which matches the current behavior.

### Why?

Next.js already supports Vite’s `import.meta.glob` API at runtime, but
its TypeScript declarations don’t support [Vite’s module
generic](https://github.com/vitejs/vite/blob/57fea001d154e7dd8d5d74d3082731f1dcfd31be/packages/vite/types/importGlob.d.ts#L113-L130).

Because of this, a typed glob works in Vite but fails in Next.js:

```text
TS2558: Expected 0 type arguments, but got 1.
```

Consumers currently have to cast the result or add their own
`ImportMeta` declaration to describe the matched modules. Supporting the
generic removes the need for those workarounds and makes typed glob
imports consistent between Next.js and Vite.

### How?

Each existing overload now accepts a generic module type, `M`, which
defaults to `unknown`:

- Lazy imports return `Record<string, () => Promise<M>>`.
- Eager imports return `Record<string, M>`.

Using `unknown` as the default means existing calls without a generic
keep the same types as before.

I also updated the existing e2e fixture. It had an old local
`ImportMeta.glob` declaration that returned `Record<string, any>`.
Removing that declaration exposed the missing generic and allowed the
five `as any` casts in the fixture to be removed. Without the generic,
all five glob calls fail during `next build` with `TS2558`. With it, all
five pass.

The Turbopack documentation has also been updated with examples showing
how to use the generic with lazy and eager imports.

### Checklist

- [x] `pnpm --filter=next types` passes
- [x] `pnpm prettier-fix` run
- [x] Documentation follows the docs contribution guide
- [x] E2E test passes

---------
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 0324a9ae
...@@ -278,6 +278,21 @@ const lazy = import.meta.glob('./dir/*.ts') ...@@ -278,6 +278,21 @@ const lazy = import.meta.glob('./dir/*.ts')
const eager = import.meta.glob('./dir/*.ts', { eager: true }) const eager = import.meta.glob('./dir/*.ts', { eager: true })
``` ```
Pass the module type to describe what the matched files export:
```ts
interface Mod {
name: string
default: () => string
}
// Record<string, () => Promise<Mod>>
const lazy = import.meta.glob<Mod>('./dir/*.ts')
// Record<string, Mod>
const eager = import.meta.glob<Mod>('./dir/*.ts', { eager: true })
```
### Options reference ### Options reference
| Option | Type | Default | Description | | Option | Type | Default | Description |
......
...@@ -130,19 +130,22 @@ interface ImportMeta { ...@@ -130,19 +130,22 @@ interface ImportMeta {
* *
* // Eager — values are module objects * // Eager — values are module objects
* const modules = import.meta.glob('./dir/*.js', { eager: true }) * const modules = import.meta.glob('./dir/*.js', { eager: true })
*
* // The module type can be provided
* const modules = import.meta.glob<{ name: string }>('./dir/*.js')
*/ */
glob( glob<M = unknown>(
pattern: string | string[], pattern: string | string[],
options: ImportMetaGlobOptions & { eager: true } options: ImportMetaGlobOptions & { eager: true }
): Record<string, unknown> ): Record<string, M>
glob( glob<M = unknown>(
pattern: string | string[], pattern: string | string[],
options?: ImportMetaGlobOptions & { eager?: false | undefined } options?: ImportMetaGlobOptions & { eager?: false | undefined }
): Record<string, () => Promise<unknown>> ): Record<string, () => Promise<M>>
glob( glob<M = unknown>(
pattern: string | string[], pattern: string | string[],
options?: ImportMetaGlobOptions options?: ImportMetaGlobOptions
): Record<string, unknown> | Record<string, () => Promise<unknown>> ): Record<string, M> | Record<string, () => Promise<M>>
} }
interface Window { interface Window {
......
interface Mod {
name: string
default: () => string
}
// Lazy glob // Lazy glob
const lazyModules = import.meta.glob('./modules/*.ts') const lazyModules = import.meta.glob<Mod>('./modules/*.ts')
// Eager glob // Eager glob
const eagerModules = import.meta.glob('./modules/*.ts', { eager: true }) const eagerModules = import.meta.glob<Mod>('./modules/*.ts', { eager: true })
// Named import (eager) // Named import (eager)
const defaultExports = import.meta.glob('./modules/*.ts', { const defaultExports = import.meta.glob<Mod['default']>('./modules/*.ts', {
import: 'default', import: 'default',
eager: true, eager: true,
}) })
// Negative pattern // Negative pattern
const filteredModules = import.meta.glob(['./modules/*.ts', '!**/skip.ts'], { const filteredModules = import.meta.glob<Mod>(
['./modules/*.ts', '!**/skip.ts'],
{
eager: true, eager: true,
}) }
)
// Multiple patterns (modules + other) // Multiple patterns (modules + other)
const multiModules = import.meta.glob(['./modules/*.ts', './other/*.ts'], { const multiModules = import.meta.glob<Mod>(['./modules/*.ts', './other/*.ts'], {
eager: true, eager: true,
}) })
...@@ -26,35 +34,35 @@ export default async function Page() { ...@@ -26,35 +34,35 @@ export default async function Page() {
const lazyResults: Record<string, string> = {} const lazyResults: Record<string, string> = {}
for (const key of lazyKeys) { for (const key of lazyKeys) {
const mod = await lazyModules[key]() const mod = await lazyModules[key]()
lazyResults[key] = (mod as any).name lazyResults[key] = mod.name
} }
// Get eager module names // Get eager module names
const eagerKeys = Object.keys(eagerModules).sort() const eagerKeys = Object.keys(eagerModules).sort()
const eagerResults: Record<string, string> = {} const eagerResults: Record<string, string> = {}
for (const key of eagerKeys) { for (const key of eagerKeys) {
eagerResults[key] = (eagerModules[key] as any).name eagerResults[key] = eagerModules[key].name
} }
// Get default exports // Get default exports
const defaultKeys = Object.keys(defaultExports).sort() const defaultKeys = Object.keys(defaultExports).sort()
const defaultResults: Record<string, string> = {} const defaultResults: Record<string, string> = {}
for (const key of defaultKeys) { for (const key of defaultKeys) {
defaultResults[key] = (defaultExports[key] as any)() defaultResults[key] = defaultExports[key]()
} }
// Get filtered module names (skip.ts should be excluded) // Get filtered module names (skip.ts should be excluded)
const filteredKeys = Object.keys(filteredModules).sort() const filteredKeys = Object.keys(filteredModules).sort()
const filteredResults: Record<string, string> = {} const filteredResults: Record<string, string> = {}
for (const key of filteredKeys) { for (const key of filteredKeys) {
filteredResults[key] = (filteredModules[key] as any).name filteredResults[key] = filteredModules[key].name
} }
// Get multi-pattern results (modules + other) // Get multi-pattern results (modules + other)
const multiKeys = Object.keys(multiModules).sort() const multiKeys = Object.keys(multiModules).sort()
const multiResults: Record<string, string> = {} const multiResults: Record<string, string> = {}
for (const key of multiKeys) { for (const key of multiKeys) {
multiResults[key] = (multiModules[key] as any).name multiResults[key] = multiModules[key].name
} }
return ( return (
......
// Augment ImportMeta with glob for Vite-compatible import.meta.glob support
interface ImportMeta {
glob(
pattern: string | string[],
options?: {
eager?: boolean
import?: string
query?: string
base?: string
}
): Record<string, any>
}
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