Unverified Commit 3ae062a1 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

fix(turbopack): support `type: 'text'` in rules, and error on binding imports of…

fix(turbopack): support `type: 'text'` in rules, and error on binding imports of non-ESM modules (#96558)

`TurbopackModuleType` has listed `'text'` for a while, but the config
schema
and `ConfiguredModuleType::parse` both rejected it. It now maps to the
existing
`TextSourceTransform` (the same thing `import … with { type: 'text' }`
uses).
`'json'`, which Rust already accepted, is added to the TypeScript type
and
schema too.

`type: 'raw'` has always been documented as "Return raw contents as
string",
but it mapped to an opaque module with no exports instead — that
mismatch is
why `import * as ns from './alpha.md'` with `{ '*.md': { type: 'raw' }
}`
evaluated to `undefined`. `raw` is now an alias of `text`: both run the
file
through `TextSourceTransform` and export its contents as a string.
Neither
name is deprecated; `text` remains the descriptive spelling that matches
the
`import … with { type: 'text' }` import attribute, `raw` keeps working
exactly
as documented. No configuration value maps to the opaque module type
anymore;
`type: 'asset'` remains the way to emit a file and get its URL.

This is also what makes Vite's `?raw` workable: Turbopack has no
built-in
`?raw` handling, so a `{ condition: { query: '?raw' }, type: 'text' }`
(or
`'raw'`) rule is what turns those files into strings. Docs previously
implied
`?raw`/`?url` worked standalone; that's corrected, and the module type
table
is completed and describes `raw`/`text` as equivalent.

Reading a binding off a module that genuinely can't be placed in an
ECMAScript chunk (a stylesheet, a native addon, …) used to evaluate to
`undefined` with no diagnostic; it now reports an error naming the
module.
Side-effect-only imports still work.

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarvercel-fleet[bot] <308483924+vercel-fleet[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 0fd0b3e3
...@@ -530,7 +530,9 @@ properties with no changes needed. `BASE_URL` reflects the Next.js ...@@ -530,7 +530,9 @@ properties with no changes needed. `BASE_URL` reflects the Next.js
[`basePath`](/docs/app/api-reference/config/next-config-js/basePath) configuration and includes a [`basePath`](/docs/app/api-reference/config/next-config-js/basePath) configuration and includes a
trailing slash, matching Vite's format. trailing slash, matching Vite's format.
**`import.meta.glob`** is supported by Turbopack (the default Next.js bundler) with no changes needed. If you were using the `as` option (deprecated in Vite 5), replace it with `query`: **`import.meta.glob`** is supported by Turbopack (the default Next.js bundler) with no changes needed.
Turbopack has no built-in handling for Vite's `?raw` and `?url` queries, so the `as` option (deprecated in Vite 5) and its `query` replacement need a matching rule in `next.config.ts`:
```js ```js
// Before (Vite) // Before (Vite)
...@@ -540,6 +542,21 @@ const modules = import.meta.glob('./dir/*.txt', { as: 'raw' }) ...@@ -540,6 +542,21 @@ const modules = import.meta.glob('./dir/*.txt', { as: 'raw' })
const modules = import.meta.glob('./dir/*.txt', { query: '?raw' }) const modules = import.meta.glob('./dir/*.txt', { query: '?raw' })
``` ```
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
rules: {
// Any file imported with `?raw` is loaded as a string
'*': { condition: { query: '?raw' }, type: 'text' },
},
},
}
export default nextConfig
```
See the [import.meta.glob docs](/docs/app/api-reference/turbopack#importmetaglob) for the full API. See the [import.meta.glob docs](/docs/app/api-reference/turbopack#importmetaglob) for the full API.
If your Vite application configured a custom base URL, set the equivalent If your Vite application configured a custom base URL, set the equivalent
......
...@@ -293,9 +293,12 @@ Available module types: ...@@ -293,9 +293,12 @@ Available module types:
| `typescript` | Process as TypeScript | | `typescript` | Process as TypeScript |
| `css` | Process as CSS | | `css` | Process as CSS |
| `css-module` | Process as CSS module | | `css-module` | Process as CSS module |
| `json` | Parse as JSON and export it |
| `wasm` | Process as WebAssembly | | `wasm` | Process as WebAssembly |
| `raw` | Return raw contents as string | | `node` | Process as a native Node.js addon |
| `bytes` | Inline contents as bytes | | `raw` | Export the contents as a string (an alias of `text`) |
| `text` | Export the contents as a string |
| `bytes` | Export the contents as a `Uint8Array` |
### Inline loader configuration with import attributes ### Inline loader configuration with import attributes
......
...@@ -220,11 +220,10 @@ const setups = import.meta.glob('./dir/*.js', { import: 'setup', eager: true }) ...@@ -220,11 +220,10 @@ const setups = import.meta.glob('./dir/*.js', { import: 'setup', eager: true })
### Query strings ### Query strings
Use the `query` option to append a query string to every import request. This is useful for loading files as raw strings or URLs: Use the `query` option to append a query string to every import request:
```js ```js
const rawFiles = import.meta.glob('./dir/*.txt', { query: '?raw' }) const rawFiles = import.meta.glob('./dir/*.txt', { query: '?raw' })
const urls = import.meta.glob('./dir/*.png', { query: '?url' })
``` ```
The `query` option also accepts an object. Keys and values are URL-encoded and joined into a query string: The `query` option also accepts an object. Keys and values are URL-encoded and joined into a query string:
...@@ -236,6 +235,23 @@ const modules = import.meta.glob('./*.ts', { ...@@ -236,6 +235,23 @@ const modules = import.meta.glob('./*.ts', {
// equivalent to: { query: '?bar=foo&raw=true' } // equivalent to: { query: '?bar=foo&raw=true' }
``` ```
The query is passed through to the module rules, it has no meaning on its own. Unlike Vite, Turbopack has no built-in `?raw` or `?url` handling, so match the query with a [rule](/docs/app/api-reference/config/next-config-js/turbopack#module-types) to decide how those files are loaded:
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
turbopack: {
rules: {
// `import.meta.glob('./dir/*.txt', { query: '?raw' })` returns the file contents as strings
'*.txt': { condition: { query: '?raw' }, type: 'text' },
},
},
}
export default nextConfig
```
### Multiple patterns and negation ### Multiple patterns and negation
Pass an array of glob patterns as the first argument. Prefix a pattern with `!` to exclude matching files: Pass an array of glob patterns as the first argument. Prefix a pattern with `!` to exclude matching files:
...@@ -272,7 +288,7 @@ const eager = import.meta.glob('./dir/*.ts', { eager: true }) ...@@ -272,7 +288,7 @@ const eager = import.meta.glob('./dir/*.ts', { eager: true })
| `base` | `string` | `undefined` | Override the base path used for resolving patterns and keying results. | | `base` | `string` | `undefined` | Override the base path used for resolving patterns and keying results. |
| `caseSensitive` | `boolean` | `true` | Match glob patterns case-sensitively. Set to `false` to ignore ASCII case. | | `caseSensitive` | `boolean` | `true` | Match glob patterns case-sensitively. Set to `false` to ignore ASCII case. |
> **Note:** The `as` option (deprecated in Vite 5) is not supported. Use `query: '?raw'` or `query: '?url'` instead. The legacy `import.meta.globEager()` API is also not supported — use `import.meta.glob('...', { eager: true })` instead. > **Note:** The `as` option (deprecated in Vite 5) is not supported. Use `query` together with a matching rule instead, as shown in [Query strings](#query-strings). The legacy `import.meta.globEager()` API is also not supported — use `import.meta.glob('...', { eager: true })` instead.
## Known gaps with webpack ## Known gaps with webpack
......
...@@ -142,10 +142,12 @@ const zTurbopackModuleType = z.enum([ ...@@ -142,10 +142,12 @@ const zTurbopackModuleType = z.enum([
'typescript', 'typescript',
'css', 'css',
'css-module', 'css-module',
'json',
'wasm', 'wasm',
'raw', 'raw',
'node', 'node',
'bytes', 'bytes',
'text',
]) ])
const zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> = const zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> =
......
...@@ -169,10 +169,12 @@ export type TurbopackRuleCondition = ...@@ -169,10 +169,12 @@ export type TurbopackRuleCondition =
* - `'typescript'` - Process as TypeScript module * - `'typescript'` - Process as TypeScript module
* - `'css'` - Process as CSS file * - `'css'` - Process as CSS file
* - `'css-module'` - Process as CSS module * - `'css-module'` - Process as CSS module
* - `'json'` - Parse as JSON and export it
* - `'wasm'` - Process as WebAssembly module * - `'wasm'` - Process as WebAssembly module
* - `'raw'` - Return raw file contents as a string * - `'raw'` - Export file contents as a string (an alias of `'text'`)
* - `'node'` - Process as native Node.js addon * - `'node'` - Process as native Node.js addon
* - `'bytes'` - Inline file contents as bytes in JavaScript * - `'bytes'` - Export file contents as a `Uint8Array`
* - `'text'` - Export file contents as a string
* *
* @see [Module Types](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#module-types) * @see [Module Types](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#module-types)
*/ */
...@@ -182,6 +184,7 @@ export type TurbopackModuleType = ...@@ -182,6 +184,7 @@ export type TurbopackModuleType =
| 'typescript' | 'typescript'
| 'css' | 'css'
| 'css-module' | 'css-module'
| 'json'
| 'wasm' | 'wasm'
| 'raw' | 'raw'
| 'node' | 'node'
......
// `alpha.md` is loaded by a `type: 'raw'` rule, `alpha.mdx` by a `type: 'text'`
// rule. The files have identical contents, so the imports must be identical.
// @ts-expect-error -- untyped module
import raw from './alpha.md'
// @ts-expect-error -- untyped module
import text from './alpha.mdx'
export default function Page() {
return (
<>
<p id="raw">{JSON.stringify(raw)}</p>
<p id="equal">{String(raw === text)}</p>
</>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
// Same as `/raw`, but the rule matching `?raw` is spelled `type: 'raw'`.
const texts = import.meta.glob('./content/*.rst', {
query: '?raw',
eager: true,
}) as Record<string, { default: string }>
export default function Page() {
return (
<ul>
{Object.keys(texts).map((key) => (
<li key={key} id={key}>
{key}: {texts[key].default.trim()}
</li>
))}
</ul>
)
}
const texts = import.meta.glob('./content/*.txt', {
query: '?raw',
eager: true,
}) as Record<string, { default: string }>
export default function Page() {
return (
<ul>
{Object.keys(texts).map((key) => (
<li key={key} id={key}>
{key}: {texts[key].default.trim()}
</li>
))}
</ul>
)
}
import { nextTestSetup } from 'e2e-utils'
// `turbopack.rules` is a Turbopack-only feature; skip under webpack
const testFn =
process.env.IS_WEBPACK_TEST || process.env.NEXT_RSPACK
? describe.skip
: describe
testFn('turbopack `text` / `raw` module types', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should load matched files as strings through a `?raw` rule', async () => {
const $ = await next.render$('/raw')
const items = $('li')
.map((_, el) => $(el).text())
.get()
expect(items).toEqual([
'./content/delta.txt: delta contents',
'./content/gamma.txt: gamma contents',
])
})
it('should treat `raw` and `text` the same in a `?raw` rule', async () => {
const $ = await next.render$('/raw-alias')
const items = $('li')
.map((_, el) => $(el).text())
.get()
expect(items).toEqual([
'./content/delta.rst: delta contents',
'./content/gamma.rst: gamma contents',
])
})
it('should treat `raw` and `text` the same for a plain import', async () => {
const $ = await next.render$('/alias')
expect(JSON.parse($('#raw').text())).toBe('# alpha\n\nsome markdown\n')
expect($('#equal').text()).toBe('true')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
turbopack: {
rules: {
// Turbopack has no built-in `?raw` handling, the query is matched by a
// rule. `raw` and `text` are aliases, both load the file as a string.
'*.txt': { condition: { query: '?raw' }, type: 'text' },
'*.rst': { condition: { query: '?raw' }, type: 'raw' },
'*.md': { type: 'raw' },
'*.mdx': { type: 'text' },
},
},
}
module.exports = nextConfig
// A `.node` addon is not placeable in an ECMAScript chunk, so it has no
// bindings to read. Reading one must be reported, not silently be `undefined`.
// @ts-expect-error -- untyped native addon
import * as ns from '../../../lib/fake.node'
export function GET() {
return Response.json({ type: typeof ns })
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('importing bindings from a module with no ECMAScript exports', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
})
if (!isTurbopack) {
it('is turbopack-only', () => {})
return
}
it('should report an error instead of silently evaluating to undefined', async () => {
const { cliOutput, exitCode } = await next.build()
expect(exitCode).not.toBe(0)
expect(cliOutput).toContain('fake.node')
expect(cliOutput).toContain('has no ECMAScript exports')
})
})
...@@ -151,7 +151,9 @@ impl AsyncModule { ...@@ -151,7 +151,9 @@ impl AsyncModule {
} }
} }
ReferencedAsset::External(..) => None, ReferencedAsset::External(..) => None,
ReferencedAsset::None | ReferencedAsset::Unresolvable => None, ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None
| ReferencedAsset::Unresolvable => None,
}) })
}) })
.try_flat_join() .try_flat_join()
......
...@@ -19,7 +19,10 @@ use turbo_tasks::{ ...@@ -19,7 +19,10 @@ use turbo_tasks::{
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkingContext, ChunkingType, ModuleChunkItemIdExt}, chunk::{ChunkingContext, ChunkingType, ModuleChunkItemIdExt},
issue::{Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString}, issue::{
Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString,
code_gen::CodeGenerationIssue,
},
loader::{ResolvedWebpackLoaderItem, WebpackLoaderItem}, loader::{ResolvedWebpackLoaderItem, WebpackLoaderItem},
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
module_graph::binding_usage_info::ModuleExportUsageInfo, module_graph::binding_usage_info::ModuleExportUsageInfo,
...@@ -59,6 +62,11 @@ use crate::{ ...@@ -59,6 +62,11 @@ use crate::{
pub enum ReferencedAsset { pub enum ReferencedAsset {
Some(ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>), Some(ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>),
External(RcStr, ExternalType), External(RcStr, ExternalType),
/// The request resolved to a module that can't be placed in an ECMAScript
/// chunk (e.g. a stylesheet or a raw module), so it has no bindings to
/// import. Importing it for its side effects is fine, reading a binding off
/// it is not.
NonPlaceable(ResolvedVc<Box<dyn Module>>),
None, None,
Unresolvable, Unresolvable,
} }
...@@ -316,6 +324,34 @@ impl ReferencedAsset { ...@@ -316,6 +324,34 @@ impl ReferencedAsset {
import_source, import_source,
}) })
} }
ReferencedAsset::NonPlaceable(module) => {
// The module exists but has no ECMAScript bindings, so there is
// nothing this identifier could refer to. Report it instead of
// silently evaluating to `undefined`.
CodeGenerationIssue {
severity: IssueSeverity::Error,
title: StyledString::Text(rcstr!("non-ecmascript placeable asset"))
.resolved_cell(),
message: StyledString::Text(
format!(
"{} has no ECMAScript exports, so {} can't be read from it. It can \
only be imported for its side effects.",
module.ident().to_string().await?,
match &export {
Some(export) => format!("the export {export:?}"),
None => "a namespace".to_string(),
}
)
.into(),
)
.resolved_cell(),
path: module.ident().await?.path.clone(),
source: None,
}
.resolved_cell()
.emit();
None
}
ReferencedAsset::None | ReferencedAsset::Unresolvable => None, ReferencedAsset::None | ReferencedAsset::Unresolvable => None,
}) })
} }
...@@ -338,6 +374,7 @@ impl ReferencedAsset { ...@@ -338,6 +374,7 @@ impl ReferencedAsset {
if result.is_unresolvable() { if result.is_unresolvable() {
return Ok(ReferencedAsset::Unresolvable); return Ok(ReferencedAsset::Unresolvable);
} }
let mut non_placeable = None;
for (_, result) in result.primary.iter() { for (_, result) in result.primary.iter() {
match result { match result {
ModuleResolveResultItem::External { ModuleResolveResultItem::External {
...@@ -351,12 +388,16 @@ impl ReferencedAsset { ...@@ -351,12 +388,16 @@ impl ReferencedAsset {
{ {
return Ok(ReferencedAsset::Some(placeable)); return Ok(ReferencedAsset::Some(placeable));
} }
non_placeable = non_placeable.or(Some(*module));
} }
// TODO ignore should probably be handled differently // TODO ignore should probably be handled differently
_ => {} _ => {}
} }
} }
Ok(ReferencedAsset::None) Ok(match non_placeable {
Some(module) => ReferencedAsset::NonPlaceable(module),
None => ReferencedAsset::None,
})
} }
} }
...@@ -740,7 +781,9 @@ impl EsmAssetReference { ...@@ -740,7 +781,9 @@ impl EsmAssetReference {
stmt, stmt,
)); ));
} }
ReferencedAsset::None => {} // A module without ECMAScript bindings (e.g. a stylesheet) may still
// be imported for its side effects, which needs no code generation.
ReferencedAsset::None | ReferencedAsset::NonPlaceable(_) => {}
_ => { _ => {
let mut result = vec![]; let mut result = vec![];
......
...@@ -216,7 +216,9 @@ impl UrlAssetReferenceCodeGen { ...@@ -216,7 +216,9 @@ impl UrlAssetReferenceCodeGen {
request request
) )
} }
ReferencedAsset::None | ReferencedAsset::Unresolvable => {} ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None
| ReferencedAsset::Unresolvable => {}
} }
} }
UrlRewriteBehavior::Full => { UrlRewriteBehavior::Full => {
...@@ -333,7 +335,9 @@ impl UrlAssetReferenceCodeGen { ...@@ -333,7 +335,9 @@ impl UrlAssetReferenceCodeGen {
request request
) )
} }
ReferencedAsset::None | ReferencedAsset::Unresolvable => {} ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None
| ReferencedAsset::Unresolvable => {}
} }
} }
UrlRewriteBehavior::None => { UrlRewriteBehavior::None => {
......
...@@ -12,7 +12,7 @@ use turbopack_core::{ ...@@ -12,7 +12,7 @@ use turbopack_core::{
use turbopack_css::CssModuleType; use turbopack_css::CssModuleType;
use turbopack_ecmascript::{ use turbopack_ecmascript::{
EcmascriptInputTransforms, EcmascriptOptions, bytes_source_transform::BytesSourceTransform, EcmascriptInputTransforms, EcmascriptOptions, bytes_source_transform::BytesSourceTransform,
json_source_transform::JsonSourceTransform, json_source_transform::JsonSourceTransform, text_source_transform::TextSourceTransform,
}; };
use turbopack_wasm::source::WebAssemblySourceType; use turbopack_wasm::source::WebAssemblySourceType;
...@@ -193,11 +193,17 @@ pub enum ConfiguredModuleType { ...@@ -193,11 +193,17 @@ pub enum ConfiguredModuleType {
/// Implemented as a source transform, not a ModuleType. /// Implemented as a source transform, not a ModuleType.
Json, Json,
Wasm, Wasm,
/// An alias of [`ConfiguredModuleType::Text`].
Raw, Raw,
Node, Node,
/// Converts any file to an ES module exporting its contents as a Uint8Array. /// Converts any file to an ES module exporting its contents as a Uint8Array.
/// Implemented as a source transform, not a ModuleType. /// Implemented as a source transform, not a ModuleType.
Bytes, Bytes,
/// Converts any file to an ES module exporting its contents as a string.
/// Implemented as a source transform, not a ModuleType.
///
/// `Raw` is an alias of this.
Text,
} }
impl ConfiguredModuleType { impl ConfiguredModuleType {
...@@ -214,9 +220,10 @@ impl ConfiguredModuleType { ...@@ -214,9 +220,10 @@ impl ConfiguredModuleType {
"raw" => ConfiguredModuleType::Raw, "raw" => ConfiguredModuleType::Raw,
"node" => ConfiguredModuleType::Node, "node" => ConfiguredModuleType::Node,
"bytes" => ConfiguredModuleType::Bytes, "bytes" => ConfiguredModuleType::Bytes,
"text" => ConfiguredModuleType::Text,
_ => bail!( _ => bail!(
"Unknown module type: {type_str:?}. Valid types are: asset, ecmascript, \ "Unknown module type: {type_str:?}. Valid types are: asset, ecmascript, \
typescript, css, css-module, json, wasm, raw, node, bytes" typescript, css, css-module, json, wasm, raw, node, bytes, text"
), ),
}) })
} }
...@@ -242,6 +249,15 @@ impl ConfiguredModuleType { ...@@ -242,6 +249,15 @@ impl ConfiguredModuleType {
BytesSourceTransform::new().to_resolved().await?, BytesSourceTransform::new().to_resolved().await?,
)])) )]))
} }
// `raw` has always been documented as returning the contents as a string, so it
// is an alias of `text` rather than a way to get an opaque module.
ConfiguredModuleType::Text | ConfiguredModuleType::Raw => {
// Same as `Bytes`: a source transform that produces .mjs, which is then
// picked up by the standard Ecmascript rules.
ModuleRuleEffect::SourceTransforms(ResolvedVc::cell(vec![ResolvedVc::upcast(
TextSourceTransform::new().to_resolved().await?,
)]))
}
ConfiguredModuleType::Asset => { ConfiguredModuleType::Asset => {
ModuleRuleEffect::ModuleType(ModuleType::StaticUrlJs { tag: None }) ModuleRuleEffect::ModuleType(ModuleType::StaticUrlJs { tag: None })
} }
...@@ -278,7 +294,6 @@ impl ConfiguredModuleType { ...@@ -278,7 +294,6 @@ impl ConfiguredModuleType {
ConfiguredModuleType::Wasm => ModuleRuleEffect::ModuleType(ModuleType::WebAssembly { ConfiguredModuleType::Wasm => ModuleRuleEffect::ModuleType(ModuleType::WebAssembly {
source_ty: WebAssemblySourceType::Binary, source_ty: WebAssemblySourceType::Binary,
}), }),
ConfiguredModuleType::Raw => ModuleRuleEffect::ModuleType(ModuleType::Raw),
ConfiguredModuleType::Node => ModuleRuleEffect::ModuleType(ModuleType::NodeAddon), ConfiguredModuleType::Node => ModuleRuleEffect::ModuleType(ModuleType::NodeAddon),
}) })
} }
......
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