Unverified Commit 95c5e390 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

feat(turbopack): support `false` values for `resolveAlias` config (#93331)

### What?

Adds support for `false` as a value in
`experimental.turbopack.resolveAlias`, which resolves the aliased module
to an empty stub — matching webpack's long-standing behavior.

```js
// next.config.js
module.exports = {
  experimental: {
    turbopack: {
      resolveAlias: {
        'some-server-only-module': false,
      },
    },
  },
}
```

With this alias in place:
- `import * as ns from 'some-server-only-module'` → `ns` is `{}`
- `import { foo } from 'some-server-only-module'` → `foo` is `undefined`
- `import def from 'some-server-only-module'` → `def` is `undefined`
- `await import('some-server-only-module')` → resolves to `{}`
- `require('some-server-only-module')` → returns `{}`

### Why?

Webpack supports `false` as an alias target to stub out modules (e.g. to
exclude Node-only packages from client/edge bundles). Turbopack did not,
causing migration friction for projects that rely on this pattern.

### How?

Threads the `false` sentinel through the full resolution pipeline as a
new `Empty` variant:

```
false (config)
  → SubpathValue::Empty      (next-core import map)
  → ImportMapping::Empty     (turbopack-core remap)
  → ReplacedImportMapping::Empty
  → ResolveResultItem::Empty
  → ModuleResolveResultItem::Empty
  → ReferencedAsset::Empty   (ESM static imports)
  → SinglePatternMapping::Ignored  (CJS require / dynamic import)
```

For static ESM imports, `ReferencedAsset::Empty` is kept as a distinct
variant so that `binding.rs` can distinguish a namespace import (yields
`{}`) from a named/default import (yields `undefined`).

For CJS `require()` and dynamic `import()`,
`ModuleResolveResultItem::Empty` maps to the existing
`SinglePatternMapping::Ignored`, which already generates the correct
`{}` / `Promise.resolve({})` stubs — so no new code-generation path was
needed there (the redundant `Empty` variant introduced during
development was removed in a follow-up cleanup commit).

**Files changed:**
- `packages/next/src/server/config-shared.ts` — add `false` to
`resolveAlias` type
- `packages/next/src/server/config-schema.ts` — add `z.literal(false)`
to schema
- `crates/next-core/src/next_import_map.rs` — map `false` →
`SubpathValue::Empty`
- `turbopack/crates/turbopack-core/src/resolve/remap.rs` — handle
`ImportMapping::Empty`
- `turbopack/crates/turbopack-core/src/resolve/mod.rs` — propagate
`ModuleResolveResultItem::Empty`
- `turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs` —
`ReferencedAsset::Empty`
- `turbopack/crates/turbopack-ecmascript/src/references/esm/binding.rs`
— empty-module binding code-gen
- `turbopack/crates/turbopack-ecmascript/src/references/esm/url.rs` —
handle Empty in URL refs
- `turbopack/crates/turbopack-ecmascript/src/references/async_module.rs`
— skip Empty in async module analysis
-
`turbopack/crates/turbopack-ecmascript/src/references/pattern_mapping.rs`
— map Empty → Ignored

**Tests:** `test/e2e/turbopack-resolve-alias-false/` covers all five
import styles (namespace, named, default, dynamic, CJS).

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 7353da4c
use std::{collections::BTreeMap, sync::LazyLock}; use std::{borrow::Cow, collections::BTreeMap, sync::LazyLock};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use async_trait::async_trait; use async_trait::async_trait;
...@@ -17,7 +17,8 @@ use turbopack_core::{ ...@@ -17,7 +17,8 @@ use turbopack_core::{
issue::{Issue, IssueExt, IssueSeverity, IssueStage, StyledString}, issue::{Issue, IssueExt, IssueSeverity, IssueStage, StyledString},
reference_type::{CommonJsReferenceSubType, ReferenceType}, reference_type::{CommonJsReferenceSubType, ReferenceType},
resolve::{ resolve::{
AliasPattern, ExternalTraced, ExternalType, ResolveAliasMap, ResolveResult, SubpathValue, AliasKey, AliasPattern, AliasTemplate, ExternalTraced, ExternalType,
ReplacedSubpathValueResultType, ResolveAliasMap, ResolveResult, SubpathValue,
node::node_cjs_resolve_options, node::node_cjs_resolve_options,
options::{ConditionValue, ImportMap, ImportMapping, ResolvedMap}, options::{ConditionValue, ImportMap, ImportMapping, ResolvedMap},
parse::Request, parse::Request,
...@@ -1441,31 +1442,35 @@ fn export_value_to_import_mapping( ...@@ -1441,31 +1442,35 @@ fn export_value_to_import_mapping(
conditions: &BTreeMap<RcStr, ConditionValue>, conditions: &BTreeMap<RcStr, ConditionValue>,
project_path: &FileSystemPath, project_path: &FileSystemPath,
) -> Option<ResolvedVc<ImportMapping>> { ) -> Option<ResolvedVc<ImportMapping>> {
let mut result = Vec::new(); let alias_key = AliasKey::Exact;
value.add_results( let mut results = Vec::new();
value.convert().add_results(
Cow::Borrowed(""),
&alias_key,
conditions, conditions,
&ConditionValue::Unset, &ConditionValue::Unset,
&mut FxHashMap::default(), &mut FxHashMap::default(),
&mut result, &mut results,
); );
if result.is_empty() {
None let mappings: Vec<_> = results
} else { .iter()
Some(if result.len() == 1 { .filter_map(|r| match &r.ty {
ImportMapping::PrimaryAlternative(result[0].0.into(), Some(project_path.clone())) ReplacedSubpathValueResultType::Path(path) => {
.resolved_cell() let m = path.as_constant_string()?;
} else { Some(
ImportMapping::Alternatives( ImportMapping::PrimaryAlternative(m.clone(), Some(project_path.clone()))
result .resolved_cell(),
.iter() )
.map(|(m, _)| { }
ImportMapping::PrimaryAlternative((*m).into(), Some(project_path.clone())) ReplacedSubpathValueResultType::Empty => Some(ImportMapping::Empty.resolved_cell()),
.resolved_cell()
})
.collect(),
)
.resolved_cell()
}) })
.collect();
match mappings.len() {
0 => None,
1 => mappings.into_iter().next(),
_ => Some(ImportMapping::Alternatives(mappings).resolved_cell()),
} }
} }
......
...@@ -171,9 +171,13 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({ ...@@ -171,9 +171,13 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
.record( .record(
z.string(), z.string(),
z.union([ z.union([
z.literal(false),
z.string(), z.string(),
z.array(z.string()), z.array(z.string()),
z.record(z.string(), z.union([z.string(), z.array(z.string())])), z.record(
z.string(),
z.union([z.literal(false), z.string(), z.array(z.string())])
),
]) ])
) )
.optional(), .optional(),
......
...@@ -248,7 +248,7 @@ export interface TurbopackOptions { ...@@ -248,7 +248,7 @@ export interface TurbopackOptions {
*/ */
resolveAlias?: Record< resolveAlias?: Record<
string, string,
string | string[] | Record<string, string | string[]> false | string | string[] | Record<string, false | string | string[]>
> >
/** /**
......
// 'some-lib' is aliased to `false` in next.config.js.
// require() should resolve to `{}`.
const mod = require('some-lib')
export function GET() {
return Response.json({
required: mod,
})
}
// 'some-lib' is aliased to `false` in next.config.js.
// Turbopack resolves the dynamic import to `{}`; webpack's empty module interop
// resolves it to `{ default: {} }`.
export async function GET() {
const mod = await import('some-lib')
return Response.json({
dynamicImport: mod,
})
}
// 'some-lib' is aliased to `false` in next.config.js.
// Namespace import should resolve to `{}`.
import * as namespaceImport from 'some-lib'
// Named import should resolve to `undefined`.
import { someExport as namedImport } from 'some-lib'
// Turbopack resolves the default import to `undefined`; webpack's empty module
// interop resolves it to `{}`.
import defaultImport from 'some-lib'
export function GET() {
return Response.json({
namespaceImport,
namedImportIsUndefined: namedImport === undefined,
defaultImportIsUndefined: defaultImport === undefined,
})
}
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 aliases = {
// Alias a non-existent module to `false` to resolve it as an empty module.
// The test covers each bundler's empty-module interop behavior.
'some-lib': false,
}
const nextConfig = {
turbopack: {
resolveAlias: aliases,
},
webpack(config) {
Object.assign(config.resolve.alias, aliases)
return config
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('resolve-alias-false', () => {
const isTurbopack = Boolean(process.env.IS_TURBOPACK_TEST)
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
describe('ESM static imports', () => {
it('resolves namespace import (import * as ns) to {}', async () => {
const response = JSON.parse(await next.render('/api/esm'))
expect(response.namespaceImport).toEqual({})
})
it('resolves named import (import { foo }) to undefined', async () => {
const response = JSON.parse(await next.render('/api/esm'))
expect(response.namedImportIsUndefined).toBe(true)
})
it('uses bundler-specific default import interop', async () => {
const response = JSON.parse(await next.render('/api/esm'))
expect(response.defaultImportIsUndefined).toBe(isTurbopack)
})
})
describe('dynamic import()', () => {
it('uses bundler-specific dynamic import interop', async () => {
const response = JSON.parse(await next.render('/api/dynamic'))
expect(response.dynamicImport).toEqual(isTurbopack ? {} : { default: {} })
})
})
describe('CommonJS require()', () => {
it('resolves require() to {}', async () => {
const response = JSON.parse(await next.render('/api/cjs'))
expect(response.required).toEqual({})
})
})
})
...@@ -36,7 +36,6 @@ use crate::{ ...@@ -36,7 +36,6 @@ use crate::{
raw_module::RawModule, raw_module::RawModule,
reference_type::ReferenceType, reference_type::ReferenceType,
resolve::{ resolve::{
alias_map::AliasKey,
error::{handle_resolve_error, resolve_error_severity}, error::{handle_resolve_error, resolve_error_severity},
node::{node_cjs_resolve_options, node_esm_resolve_options}, node::{node_cjs_resolve_options, node_esm_resolve_options},
options::{ options::{
...@@ -47,7 +46,7 @@ use crate::{ ...@@ -47,7 +46,7 @@ use crate::{
parse::{Request, stringify_data_uri}, parse::{Request, stringify_data_uri},
pattern::{Pattern, PatternMatch, read_matches}, pattern::{Pattern, PatternMatch, read_matches},
plugin::{AfterResolvePlugin, AfterResolvePluginCondition, BeforeResolvePlugin}, plugin::{AfterResolvePlugin, AfterResolvePluginCondition, BeforeResolvePlugin},
remap::{ExportImport, ExportsField, ImportsField, ReplacedSubpathValueResult}, remap::{ExportImport, ExportsField, ImportsField},
}, },
source::Source, source::Source,
}; };
...@@ -63,9 +62,14 @@ pub mod plugin; ...@@ -63,9 +62,14 @@ pub mod plugin;
pub(crate) mod remap; pub(crate) mod remap;
pub use alias_map::{ pub use alias_map::{
AliasMap, AliasMapIntoIter, AliasMapLookupIterator, AliasMatch, AliasPattern, AliasTemplate, AliasKey, AliasMap, AliasMapIntoIter, AliasMapLookupIterator, AliasMatch, AliasPattern,
AliasTemplate,
};
use remap::TerminalState;
pub use remap::{
ReplacedSubpathValue, ReplacedSubpathValueResult, ReplacedSubpathValueResultType,
ResolveAliasMap, SubpathValue,
}; };
pub use remap::{ResolveAliasMap, SubpathValue};
/// Controls how resolve errors are handled. /// Controls how resolve errors are handled.
#[turbo_tasks::value(shared, task_input)] #[turbo_tasks::value(shared, task_input)]
...@@ -3229,6 +3233,21 @@ async fn resolved( ...@@ -3229,6 +3233,21 @@ async fn resolved(
)) ))
} }
/// Attaches `conditions` to a resolve result.
///
/// When `conditions` is empty the original `Vc` is returned as-is to avoid an
/// unnecessary await. Otherwise the result is awaited, annotated, and re-wrapped.
async fn apply_conditions(
resolve_result: Vc<ResolveResult>,
conditions: &[(RcStr, bool)],
) -> Result<Vc<ResolveResult>> {
if conditions.is_empty() {
Ok(resolve_result)
} else {
Ok(resolve_result.await?.with_conditions(conditions).cell())
}
}
async fn handle_exports_imports_field( async fn handle_exports_imports_field(
package_path: FileSystemPath, package_path: FileSystemPath,
package_json_path: FileSystemPath, package_json_path: FileSystemPath,
...@@ -3258,73 +3277,83 @@ async fn handle_exports_imports_field( ...@@ -3258,73 +3277,83 @@ async fn handle_exports_imports_field(
unspecified_conditions, unspecified_conditions,
&mut conditions_state, &mut conditions_state,
&mut results, &mut results,
) { ) != TerminalState::Unset
// Match found, stop (leveraging the lazy `lookup` iterator). {
// A definitive match was found (results added or import blocked);
// stop iterating over further alias entries.
break; break;
} }
} }
let mut resolved_results = Vec::new(); let mut resolved_results = Vec::new();
for ReplacedSubpathValueResult { for ReplacedSubpathValueResult {
result_path, ty: result_ty,
conditions, conditions,
map_prefix, map_prefix,
map_key, map_key,
} in results } in results
{ {
let request = match ty { match result_ty {
ExportImport::Export => { ReplacedSubpathValueResultType::Path(result_path) => {
// Only relative paths are allowed in exports fields let request = match ty {
Pattern::Concatenation(vec![Pattern::Constant(rcstr!("./")), result_path.clone()]) ExportImport::Export => {
} // Only relative paths are allowed in exports fields
ExportImport::Import => result_path.clone(), Pattern::Concatenation(vec![
}; Pattern::Constant(rcstr!("./")),
let request = *Request::parse(request).to_resolved().await?; result_path.clone(),
])
}
ExportImport::Import => result_path.clone(),
};
let request = *Request::parse(request).to_resolved().await?;
let resolve_result = Box::pin(resolve_internal_inline( let resolve_result = Box::pin(resolve_internal_inline(
package_path.clone(), package_path.clone(),
request, request,
options, options,
)) ))
.await?; .await?;
let resolve_result = if let Some(req) = req.as_constant_string() { let resolve_result = if let Some(req) = req.as_constant_string() {
resolve_result.with_request(req.clone()) resolve_result.with_request(req.clone())
} else { } else {
match map_key { match map_key {
AliasKey::Exact => resolve_result.with_request(map_prefix.clone().into()), AliasKey::Exact => resolve_result.with_request(map_prefix.clone().into()),
AliasKey::Wildcard { .. } => { AliasKey::Wildcard { .. } => {
// - `req` is the user's request (key of the export map) // - `req` is the user's request (key of the export map)
// - `result_path` is the final request (value of the export map), so // - `result_path` is the final request (value of the export map), so
// effectively `'{foo}*{bar}'` // effectively `'{foo}*{bar}'`
// Because of the assertion in AliasMapLookupIterator, `req` is of the // Because of the assertion in AliasMapLookupIterator, `req` is of the
// form: // form:
// - "prefix...<dynamic>" or // - "prefix...<dynamic>" or
// - "prefix...<dynamic>...suffix" // - "prefix...<dynamic>...suffix"
let mut old_request_key = result_path; let mut old_request_key = result_path;
if matches!(ty, ExportImport::Export) { if matches!(ty, ExportImport::Export) {
// Remove the Pattern::Constant(rcstr!("./")) from above again // Remove the Pattern::Constant(rcstr!("./")) from above again
old_request_key.push_front(rcstr!("./").into()); old_request_key.push_front(rcstr!("./").into());
}
let new_request_key = req.clone();
resolve_result.with_replaced_request_key_pattern(
Pattern::new(old_request_key),
Pattern::new(new_request_key),
)
}
} }
let new_request_key = req.clone(); };
resolve_result.with_replaced_request_key_pattern( let resolve_result = apply_conditions(resolve_result, &conditions).await?;
Pattern::new(old_request_key), resolved_results.push(resolve_result);
Pattern::new(new_request_key),
)
}
} }
}; ReplacedSubpathValueResultType::Empty => {
// `false` in the exports/imports field: resolve to an empty module.
let resolve_result = if !conditions.is_empty() { let resolve_result = ResolveResult::primary(ResolveResultItem::Empty).cell();
let resolve_result = resolve_result.await?.with_conditions(&conditions); let resolve_result = apply_conditions(resolve_result, &conditions).await?;
resolve_result.cell() resolved_results.push(resolve_result);
} else { }
resolve_result }
};
resolved_results.push(resolve_result);
} }
// other options do not apply anymore when an exports field exist // other options do not apply anymore when an exports field exist
......
...@@ -153,6 +153,7 @@ impl AsyncModule { ...@@ -153,6 +153,7 @@ impl AsyncModule {
ReferencedAsset::External(..) => None, ReferencedAsset::External(..) => None,
ReferencedAsset::NonPlaceable(_) ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None | ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::Unresolvable => None, | ReferencedAsset::Unresolvable => None,
}) })
}) })
......
...@@ -69,6 +69,8 @@ pub enum ReferencedAsset { ...@@ -69,6 +69,8 @@ pub enum ReferencedAsset {
/// it is not. /// it is not.
NonPlaceable(ResolvedVc<Box<dyn Module>>), NonPlaceable(ResolvedVc<Box<dyn Module>>),
None, None,
/// The module was aliased to `false`, resolving to an empty module.
Empty,
Unresolvable, Unresolvable,
} }
...@@ -362,7 +364,7 @@ impl ReferencedAsset { ...@@ -362,7 +364,7 @@ impl ReferencedAsset {
.emit(); .emit();
None None
} }
ReferencedAsset::None | ReferencedAsset::Unresolvable => None, ReferencedAsset::None | ReferencedAsset::Empty | ReferencedAsset::Unresolvable => None,
}) })
} }
...@@ -400,6 +402,9 @@ impl ReferencedAsset { ...@@ -400,6 +402,9 @@ impl ReferencedAsset {
} }
non_placeable = non_placeable.or(Some(*module)); non_placeable = non_placeable.or(Some(*module));
} }
ModuleResolveResultItem::Empty => {
return Ok(ReferencedAsset::Empty);
}
// TODO ignore should probably be handled differently // TODO ignore should probably be handled differently
_ => {} _ => {}
} }
...@@ -836,7 +841,9 @@ impl EsmAssetReference { ...@@ -836,7 +841,9 @@ impl EsmAssetReference {
} }
// A module without ECMAScript bindings (e.g. a stylesheet) may still // A module without ECMAScript bindings (e.g. a stylesheet) may still
// be imported for its side effects, which needs no code generation. // be imported for its side effects, which needs no code generation.
ReferencedAsset::None | ReferencedAsset::NonPlaceable(_) => {} ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::NonPlaceable(_) => {}
_ => { _ => {
let mut result = vec![]; let mut result = vec![];
......
...@@ -77,11 +77,22 @@ impl EsmBinding { ...@@ -77,11 +77,22 @@ impl EsmBinding {
enum ImportedIdent { enum ImportedIdent {
Module(ReferencedAssetIdent), Module(ReferencedAssetIdent),
None, None,
/// Empty module (alias set to `false`): namespace imports resolve to `{}`.
Empty,
Unresolvable, Unresolvable,
} }
let imported_ident = match &imported_module { let imported_ident = match &imported_module {
ReferencedAsset::None => ImportedIdent::None, ReferencedAsset::None => ImportedIdent::None,
ReferencedAsset::Empty => {
if export.is_some() {
// Named/default binding from an empty module → `undefined`
ImportedIdent::None
} else {
// Namespace import from an empty module → `{}`
ImportedIdent::Empty
}
}
imported_module => imported_module imported_module => imported_module
.get_ident(chunking_context, export, scope_hoisting_context) .get_ident(chunking_context, export, scope_hoisting_context)
.await? .await?
...@@ -119,6 +130,13 @@ impl EsmBinding { ...@@ -119,6 +130,13 @@ impl EsmBinding {
value: Expr::undefined(ident.span), value: Expr::undefined(ident.span),
}); });
} }
ImportedIdent::Empty => {
use swc_core::quote;
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(ident.clone().into()),
value: Box::new(quote!("{}" as Expr)),
});
}
ImportedIdent::Unresolvable => { ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw // Do nothing, the reference will insert a throw
} }
...@@ -153,6 +171,10 @@ impl EsmBinding { ...@@ -153,6 +171,10 @@ impl EsmBinding {
ImportedIdent::None => { ImportedIdent::None => {
*expr = *Expr::undefined(expr.span()); *expr = *Expr::undefined(expr.span());
} }
ImportedIdent::Empty => {
use swc_core::quote;
*expr = quote!("{}" as Expr);
}
ImportedIdent::Unresolvable => { ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw // Do nothing, the reference will insert a throw
} }
...@@ -183,8 +205,8 @@ impl EsmBinding { ...@@ -183,8 +205,8 @@ impl EsmBinding {
) )
.into_inner(); .into_inner();
} }
ImportedIdent::None => { ImportedIdent::None | ImportedIdent::Empty => {
// Do nothing, cannot assign to `undefined` // Do nothing, cannot assign to `undefined` or `{}`
} }
ImportedIdent::Unresolvable => { ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw // Do nothing, the reference will insert a throw
......
...@@ -225,6 +225,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -225,6 +225,7 @@ impl UrlAssetReferenceCodeGen {
} }
ReferencedAsset::NonPlaceable(_) ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None | ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::Unresolvable => {} | ReferencedAsset::Unresolvable => {}
} }
} }
...@@ -338,6 +339,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -338,6 +339,7 @@ impl UrlAssetReferenceCodeGen {
} }
ReferencedAsset::NonPlaceable(_) ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None | ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::Unresolvable => {} | ReferencedAsset::Unresolvable => {}
} }
} }
......
...@@ -374,7 +374,9 @@ async fn to_single_pattern_mapping( ...@@ -374,7 +374,9 @@ async fn to_single_pattern_mapping(
)) ))
.await; .await;
} }
ModuleResolveResultItem::Empty | ModuleResolveResultItem::Custom(_) => { // `false` alias — no backing asset, produces the same empty-stub code as Ignored.
ModuleResolveResultItem::Empty => return Ok(SinglePatternMapping::Ignored),
ModuleResolveResultItem::Custom(_) => {
// TODO implement mapping // TODO implement mapping
CodeGenerationIssue { CodeGenerationIssue {
severity: IssueSeverity::Bug, severity: IssueSeverity::Bug,
......
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