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 async_trait::async_trait;
......@@ -17,7 +17,8 @@ use turbopack_core::{
issue::{Issue, IssueExt, IssueSeverity, IssueStage, StyledString},
reference_type::{CommonJsReferenceSubType, ReferenceType},
resolve::{
AliasPattern, ExternalTraced, ExternalType, ResolveAliasMap, ResolveResult, SubpathValue,
AliasKey, AliasPattern, AliasTemplate, ExternalTraced, ExternalType,
ReplacedSubpathValueResultType, ResolveAliasMap, ResolveResult, SubpathValue,
node::node_cjs_resolve_options,
options::{ConditionValue, ImportMap, ImportMapping, ResolvedMap},
parse::Request,
......@@ -1441,31 +1442,35 @@ fn export_value_to_import_mapping(
conditions: &BTreeMap<RcStr, ConditionValue>,
project_path: &FileSystemPath,
) -> Option<ResolvedVc<ImportMapping>> {
let mut result = Vec::new();
value.add_results(
let alias_key = AliasKey::Exact;
let mut results = Vec::new();
value.convert().add_results(
Cow::Borrowed(""),
&alias_key,
conditions,
&ConditionValue::Unset,
&mut FxHashMap::default(),
&mut result,
&mut results,
);
if result.is_empty() {
None
} else {
Some(if result.len() == 1 {
ImportMapping::PrimaryAlternative(result[0].0.into(), Some(project_path.clone()))
.resolved_cell()
} else {
ImportMapping::Alternatives(
result
.iter()
.map(|(m, _)| {
ImportMapping::PrimaryAlternative((*m).into(), Some(project_path.clone()))
.resolved_cell()
})
.collect(),
)
.resolved_cell()
let mappings: Vec<_> = results
.iter()
.filter_map(|r| match &r.ty {
ReplacedSubpathValueResultType::Path(path) => {
let m = path.as_constant_string()?;
Some(
ImportMapping::PrimaryAlternative(m.clone(), Some(project_path.clone()))
.resolved_cell(),
)
}
ReplacedSubpathValueResultType::Empty => Some(ImportMapping::Empty.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({
.record(
z.string(),
z.union([
z.literal(false),
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(),
......
......@@ -248,7 +248,7 @@ export interface TurbopackOptions {
*/
resolveAlias?: Record<
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::{
raw_module::RawModule,
reference_type::ReferenceType,
resolve::{
alias_map::AliasKey,
error::{handle_resolve_error, resolve_error_severity},
node::{node_cjs_resolve_options, node_esm_resolve_options},
options::{
......@@ -47,7 +46,7 @@ use crate::{
parse::{Request, stringify_data_uri},
pattern::{Pattern, PatternMatch, read_matches},
plugin::{AfterResolvePlugin, AfterResolvePluginCondition, BeforeResolvePlugin},
remap::{ExportImport, ExportsField, ImportsField, ReplacedSubpathValueResult},
remap::{ExportImport, ExportsField, ImportsField},
},
source::Source,
};
......@@ -63,9 +62,14 @@ pub mod plugin;
pub(crate) mod remap;
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.
#[turbo_tasks::value(shared, task_input)]
......@@ -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(
package_path: FileSystemPath,
package_json_path: FileSystemPath,
......@@ -3258,73 +3277,83 @@ async fn handle_exports_imports_field(
unspecified_conditions,
&mut conditions_state,
&mut results,
) {
// Match found, stop (leveraging the lazy `lookup` iterator).
) != TerminalState::Unset
{
// A definitive match was found (results added or import blocked);
// stop iterating over further alias entries.
break;
}
}
let mut resolved_results = Vec::new();
for ReplacedSubpathValueResult {
result_path,
ty: result_ty,
conditions,
map_prefix,
map_key,
} in results
{
let request = match ty {
ExportImport::Export => {
// Only relative paths are allowed in exports fields
Pattern::Concatenation(vec![Pattern::Constant(rcstr!("./")), result_path.clone()])
}
ExportImport::Import => result_path.clone(),
};
let request = *Request::parse(request).to_resolved().await?;
match result_ty {
ReplacedSubpathValueResultType::Path(result_path) => {
let request = match ty {
ExportImport::Export => {
// Only relative paths are allowed in exports fields
Pattern::Concatenation(vec![
Pattern::Constant(rcstr!("./")),
result_path.clone(),
])
}
ExportImport::Import => result_path.clone(),
};
let request = *Request::parse(request).to_resolved().await?;
let resolve_result = Box::pin(resolve_internal_inline(
package_path.clone(),
request,
options,
))
.await?;
let resolve_result = Box::pin(resolve_internal_inline(
package_path.clone(),
request,
options,
))
.await?;
let resolve_result = if let Some(req) = req.as_constant_string() {
resolve_result.with_request(req.clone())
} else {
match map_key {
AliasKey::Exact => resolve_result.with_request(map_prefix.clone().into()),
AliasKey::Wildcard { .. } => {
// - `req` is the user's request (key of the export map)
// - `result_path` is the final request (value of the export map), so
// effectively `'{foo}*{bar}'`
// Because of the assertion in AliasMapLookupIterator, `req` is of the
// form:
// - "prefix...<dynamic>" or
// - "prefix...<dynamic>...suffix"
let mut old_request_key = result_path;
if matches!(ty, ExportImport::Export) {
// Remove the Pattern::Constant(rcstr!("./")) from above again
old_request_key.push_front(rcstr!("./").into());
let resolve_result = if let Some(req) = req.as_constant_string() {
resolve_result.with_request(req.clone())
} else {
match map_key {
AliasKey::Exact => resolve_result.with_request(map_prefix.clone().into()),
AliasKey::Wildcard { .. } => {
// - `req` is the user's request (key of the export map)
// - `result_path` is the final request (value of the export map), so
// effectively `'{foo}*{bar}'`
// Because of the assertion in AliasMapLookupIterator, `req` is of the
// form:
// - "prefix...<dynamic>" or
// - "prefix...<dynamic>...suffix"
let mut old_request_key = result_path;
if matches!(ty, ExportImport::Export) {
// Remove the Pattern::Constant(rcstr!("./")) from above again
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(
Pattern::new(old_request_key),
Pattern::new(new_request_key),
)
}
let resolve_result = apply_conditions(resolve_result, &conditions).await?;
resolved_results.push(resolve_result);
}
};
let resolve_result = if !conditions.is_empty() {
let resolve_result = resolve_result.await?.with_conditions(&conditions);
resolve_result.cell()
} else {
resolve_result
};
resolved_results.push(resolve_result);
ReplacedSubpathValueResultType::Empty => {
// `false` in the exports/imports field: resolve to an empty module.
let resolve_result = ResolveResult::primary(ResolveResultItem::Empty).cell();
let resolve_result = apply_conditions(resolve_result, &conditions).await?;
resolved_results.push(resolve_result);
}
}
}
// other options do not apply anymore when an exports field exist
......
......@@ -153,6 +153,7 @@ impl AsyncModule {
ReferencedAsset::External(..) => None,
ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::Unresolvable => None,
})
})
......
......@@ -69,6 +69,8 @@ pub enum ReferencedAsset {
/// it is not.
NonPlaceable(ResolvedVc<Box<dyn Module>>),
None,
/// The module was aliased to `false`, resolving to an empty module.
Empty,
Unresolvable,
}
......@@ -362,7 +364,7 @@ impl ReferencedAsset {
.emit();
None
}
ReferencedAsset::None | ReferencedAsset::Unresolvable => None,
ReferencedAsset::None | ReferencedAsset::Empty | ReferencedAsset::Unresolvable => None,
})
}
......@@ -400,6 +402,9 @@ impl ReferencedAsset {
}
non_placeable = non_placeable.or(Some(*module));
}
ModuleResolveResultItem::Empty => {
return Ok(ReferencedAsset::Empty);
}
// TODO ignore should probably be handled differently
_ => {}
}
......@@ -836,7 +841,9 @@ impl EsmAssetReference {
}
// 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(_) => {}
ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::NonPlaceable(_) => {}
_ => {
let mut result = vec![];
......
......@@ -77,11 +77,22 @@ impl EsmBinding {
enum ImportedIdent {
Module(ReferencedAssetIdent),
None,
/// Empty module (alias set to `false`): namespace imports resolve to `{}`.
Empty,
Unresolvable,
}
let imported_ident = match &imported_module {
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
.get_ident(chunking_context, export, scope_hoisting_context)
.await?
......@@ -119,6 +130,13 @@ impl EsmBinding {
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 => {
// Do nothing, the reference will insert a throw
}
......@@ -153,6 +171,10 @@ impl EsmBinding {
ImportedIdent::None => {
*expr = *Expr::undefined(expr.span());
}
ImportedIdent::Empty => {
use swc_core::quote;
*expr = quote!("{}" as Expr);
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
}
......@@ -183,8 +205,8 @@ impl EsmBinding {
)
.into_inner();
}
ImportedIdent::None => {
// Do nothing, cannot assign to `undefined`
ImportedIdent::None | ImportedIdent::Empty => {
// Do nothing, cannot assign to `undefined` or `{}`
}
ImportedIdent::Unresolvable => {
// Do nothing, the reference will insert a throw
......
......@@ -225,6 +225,7 @@ impl UrlAssetReferenceCodeGen {
}
ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::Unresolvable => {}
}
}
......@@ -338,6 +339,7 @@ impl UrlAssetReferenceCodeGen {
}
ReferencedAsset::NonPlaceable(_)
| ReferencedAsset::None
| ReferencedAsset::Empty
| ReferencedAsset::Unresolvable => {}
}
}
......
......@@ -374,7 +374,9 @@ async fn to_single_pattern_mapping(
))
.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
CodeGenerationIssue {
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