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

Allow opt-in facade-backed export mangling (#99309)

## Summary

The rollback in #99285 keeps local-only modules unsplit by default to
avoid the remote-components singleton regression in #99279. This
follow-up preserves facade-backed export mangling as an **opt-in** for
applications that benefit from shorter keys even when a namespace
escapes.

`experimental.turbopackMangleViaMaterializedNamespaceObject` controls
the split independently from `turbopackMangleExportNames`. If unset, it
is enabled only when `turbopackMangleExportNames` is explicitly `true`;
canary's implicit production mangling does **not** enable it. An
explicit `false` wins. The option reaches both server and client
Turbopack contexts; re-export splitting and ordinary export mangling are
unchanged. The config and splitting comments document the compatibility
risk for code that patches modules split into multiple parts.

## Verification

- Turbopack execution: 313 passed with the facade option enabled by
default in the **test harness**, including the original mixed-import
regression explicitly opted out and a no-export-mangling control.
Escaping-namespace fixtures also verify facade-backed mangling retains
original public names. Snapshots: 132 passed. The production defaults
are unchanged.
- Turbopack ECMAScript unit tests: 590 passed; Next core unit tests: 82
passed after removing the config-default helper test requested in
review.
- `pnpm build-all` (18/18 tasks), `pnpm --filter next types`, formatting
and lint-staged checks passed.
- Production Turbopack emit-collect fixture: 9 tests and 18 snapshots
passed with defaults.
- A scratch production Next.js app confirmed the module has facade and
`<locals>` IDs with explicit export mangling and the new option inferred
on, but no `<locals>` ID when the new option is explicitly off or both
options are omitted. The scratch app is not included.

<!-- NEXT_JS_LLM -->


<!-- fleet faf1202d-c919-4f7d-bb74-d3fe954bbc57 -->

---------
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>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent b16348a2
...@@ -374,6 +374,9 @@ pub async fn get_client_module_options_context( ...@@ -374,6 +374,9 @@ pub async fn get_client_module_options_context(
infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?, infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?,
cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?, cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?,
mangle_export_names: *next_config.turbopack_mangle_export_names(mode).await?, mangle_export_names: *next_config.turbopack_mangle_export_names(mode).await?,
mangle_via_materialized_namespace_object: *next_config
.turbopack_mangle_via_materialized_namespace_object()
.await?,
cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?, cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?,
cross_module_constants: *next_config.turbopack_cross_module_constants().await?, cross_module_constants: *next_config.turbopack_cross_module_constants().await?,
lazy_compilation: *next_config lazy_compilation: *next_config
......
...@@ -1227,6 +1227,8 @@ pub struct ExperimentalConfig { ...@@ -1227,6 +1227,8 @@ pub struct ExperimentalConfig {
/// Shorten ("mangle") the export names modules expose to each other. Defaults to false in /// Shorten ("mangle") the export names modules expose to each other. Defaults to false in
/// development mode, true in production mode. /// development mode, true in production mode.
turbopack_mangle_export_names: Option<bool>, turbopack_mangle_export_names: Option<bool>,
/// Use a materialized namespace facade to mangle otherwise observable export names.
turbopack_mangle_via_materialized_namespace_object: Option<bool>,
/// Enable scope hoisting of static CommonJS modules. Defaults to false. /// Enable scope hoisting of static CommonJS modules. Defaults to false.
turbopack_cjs_scope_hoisting: Option<bool>, turbopack_cjs_scope_hoisting: Option<bool>,
/// Enable cross-module constant inlining. Defaults to false. /// Enable cross-module constant inlining. Defaults to false.
...@@ -1241,6 +1243,13 @@ pub struct ExperimentalConfig { ...@@ -1241,6 +1243,13 @@ pub struct ExperimentalConfig {
lightning_css_features: Option<LightningCssFeatures>, lightning_css_features: Option<LightningCssFeatures>,
} }
impl ExperimentalConfig {
fn mangle_via_materialized_namespace_object(&self) -> bool {
self.turbopack_mangle_via_materialized_namespace_object
.unwrap_or(self.turbopack_mangle_export_names == Some(true))
}
}
#[derive( #[derive(
Clone, Debug, PartialEq, Eq, Deserialize, NonLocalValue, OperationValue, Encode, Decode, Clone, Debug, PartialEq, Eq, Deserialize, NonLocalValue, OperationValue, Encode, Decode,
)] )]
...@@ -2331,6 +2340,13 @@ impl NextConfig { ...@@ -2331,6 +2340,13 @@ impl NextConfig {
)) ))
} }
/// Opt into splitting local-only modules behind a namespace facade for export mangling.
/// Inferred from the explicitly configured mangling option, not its mode-dependent default.
#[turbo_tasks::function]
pub fn turbopack_mangle_via_materialized_namespace_object(&self) -> Vc<bool> {
Vc::cell(self.experimental.mangle_via_materialized_namespace_object())
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn turbopack_cjs_scope_hoisting(&self) -> Vc<bool> { pub fn turbopack_cjs_scope_hoisting(&self) -> Vc<bool> {
Vc::cell( Vc::cell(
......
...@@ -547,6 +547,9 @@ pub async fn get_server_module_options_context( ...@@ -547,6 +547,9 @@ pub async fn get_server_module_options_context(
infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?, infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?,
cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?, cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?,
mangle_export_names: *next_config.turbopack_mangle_export_names(mode).await?, mangle_export_names: *next_config.turbopack_mangle_export_names(mode).await?,
mangle_via_materialized_namespace_object: *next_config
.turbopack_mangle_via_materialized_namespace_object()
.await?,
cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?, cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?,
cross_module_constants: *next_config.turbopack_cross_module_constants().await?, cross_module_constants: *next_config.turbopack_cross_module_constants().await?,
..Default::default() ..Default::default()
......
...@@ -464,6 +464,7 @@ Additionally, the following experimental options are available under `experiment ...@@ -464,6 +464,7 @@ Additionally, the following experimental options are available under `experiment
| `turbopackRemoveUnusedImports` | Enable removing unused imports. Requires `turbopackRemoveUnusedExports`. | `false` | `true` | | `turbopackRemoveUnusedImports` | Enable removing unused imports. Requires `turbopackRemoveUnusedExports`. | `false` | `true` |
| `turbopackRemoveUnusedExports` | Enable removing unused exports. | `false` | `true` | | `turbopackRemoveUnusedExports` | Enable removing unused exports. | `false` | `true` |
| `turbopackMangleExportNames` | Shorten the export names modules expose to each other, to reduce bundle size. A module whose export names can be observed (an escaping namespace object, a dynamic `import()`, a CommonJS `require()`) keeps its original names. | `false` | `true` | | `turbopackMangleExportNames` | Shorten the export names modules expose to each other, to reduce bundle size. A module whose export names can be observed (an escaping namespace object, a dynamic `import()`, a CommonJS `require()`) keeps its original names. | `false` | `true` |
| `turbopackMangleViaMaterializedNamespaceObject` | Allow export mangling through a materialized namespace facade. Defaults to `true` when `turbopackMangleExportNames` is explicitly `true`. | `false` | `false` |
| `turbopackInferModuleSideEffects` | Enable local analysis to infer side-effect-free modules for better tree shaking. | `true` | `true` | | `turbopackInferModuleSideEffects` | Enable local analysis to infer side-effect-free modules for better tree shaking. | `true` | `true` |
| `turbopackScopeHoisting` | Enable scope hoisting. Always disabled in dev mode. | `false` | `true` | | `turbopackScopeHoisting` | Enable scope hoisting. Always disabled in dev mode. | `false` | `true` |
| `turbopackSharedRuntime` | Share the browser runtime across routes in a single `runtime.js` asset. Only applies to production builds. | N/A | `true` | | `turbopackSharedRuntime` | Share the browser runtime across routes in a single `runtime.js` asset. Only applies to production builds. | N/A | `true` |
......
...@@ -458,6 +458,7 @@ export const experimentalSchema = { ...@@ -458,6 +458,7 @@ export const experimentalSchema = {
turbopackInferModuleSideEffects: z.boolean().optional(), turbopackInferModuleSideEffects: z.boolean().optional(),
turbopackCjsTreeShaking: z.boolean().optional(), turbopackCjsTreeShaking: z.boolean().optional(),
turbopackMangleExportNames: z.boolean().optional(), turbopackMangleExportNames: z.boolean().optional(),
turbopackMangleViaMaterializedNamespaceObject: z.boolean().optional(),
turbopackCjsScopeHoisting: z.boolean().optional(), turbopackCjsScopeHoisting: z.boolean().optional(),
turbopackCrossModuleConstants: z.boolean().optional(), turbopackCrossModuleConstants: z.boolean().optional(),
turbopackServerFastRefresh: z.boolean().optional(), turbopackServerFastRefresh: z.boolean().optional(),
......
...@@ -1093,6 +1093,16 @@ export interface ExperimentalConfig { ...@@ -1093,6 +1093,16 @@ export interface ExperimentalConfig {
*/ */
turbopackMangleExportNames?: boolean turbopackMangleExportNames?: boolean
/**
* Materialize namespace objects behind a facade so their local export keys can still be
* mangled. This can interfere with code that patches modules, since a module might be split
* into multiple parts.
*
* Defaults to `true` only when `turbopackMangleExportNames` is explicitly `true`; otherwise
* defaults to `false`, including when export mangling is enabled by default.
*/
turbopackMangleViaMaterializedNamespaceObject?: boolean
/** /**
* Enable scope hoisting of static CommonJS modules. * Enable scope hoisting of static CommonJS modules.
* *
......
...@@ -323,12 +323,17 @@ impl EcmascriptExports { ...@@ -323,12 +323,17 @@ impl EcmascriptExports {
/// Returns whether this module should be split into separate locals and facade modules. /// Returns whether this module should be split into separate locals and facade modules.
/// ///
/// Splitting is enabled for modules with re-exports (star exports or imported bindings), /// Splitting is enabled for modules with re-exports (star exports or imported bindings),
/// allowing tree shaking to separate local definitions from re-exports. Do not split a /// allowing tree shaking to separate local definitions from re-exports. It can also be opted
/// local-only module merely to mangle its export names: dynamic imports would resolve to the /// into for export-name mangling, placing original names on a facade and shortened keys on
/// facade while static named imports follow through to the locals module, giving a shared /// locals. This is off by default because splitting a module into multiple parts can interfere
/// module two different runtime identities. /// with code that patches modules: patching the facade does not also patch the locals module.
/// TODO: Make the mangling-only split compatible with module patching before enabling it by
/// default (#99279).
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn split_locals_and_reexports(&self) -> Result<Vc<bool>> { pub async fn split_locals_and_reexports(
&self,
mangle_via_materialized_namespace_object: bool,
) -> Result<Vc<bool>> {
Ok(match self { Ok(match self {
EcmascriptExports::EsmExports(exports) => { EcmascriptExports::EsmExports(exports) => {
let exports = exports.await?; let exports = exports.await?;
...@@ -339,9 +344,12 @@ impl EcmascriptExports { ...@@ -339,9 +344,12 @@ impl EcmascriptExports {
EsmExport::ImportedBinding(..) | EsmExport::ImportedNamespace(_) EsmExport::ImportedBinding(..) | EsmExport::ImportedNamespace(_)
) )
}); });
// TODO: Re-enable mangling-only facade splits once remote-components consumers Vc::cell(
// can share a singleton across dynamic facade and static locals imports (#99279). has_reexports
Vc::cell(has_reexports) || (mangle_via_materialized_namespace_object
&& exports.mangle_export_names
&& !exports.exports.is_empty()),
)
} }
_ => Vc::cell(false), _ => Vc::cell(false),
}) })
......
...@@ -252,6 +252,9 @@ pub struct EcmascriptOptions { ...@@ -252,6 +252,9 @@ pub struct EcmascriptOptions {
/// reduce output size. Defaults to false. See /// reduce output size. Defaults to false. See
/// `references::esm::mangle::mangled_export_names`. /// `references::esm::mangle::mangled_export_names`.
pub mangle_export_names: bool, pub mangle_export_names: bool,
/// Whether to materialize public namespaces with a facade so local export keys can still be
/// mangled when the namespace escapes. Defaults to false and requires `mangle_export_names`.
pub mangle_via_materialized_namespace_object: bool,
/// Whether to scope hoist static CommonJS modules. Defaults to false. /// Whether to scope hoist static CommonJS modules. Defaults to false.
pub cjs_scope_hoisting: bool, pub cjs_scope_hoisting: bool,
/// Whether to enable cross-module constant inlining. Defaults to false. /// Whether to enable cross-module constant inlining. Defaults to false.
......
...@@ -33,7 +33,15 @@ pub async fn canonicalize_ecmascript_module( ...@@ -33,7 +33,15 @@ pub async fn canonicalize_ecmascript_module(
EcmascriptModulePartAsset::select_part(*module, part) EcmascriptModulePartAsset::select_part(*module, part)
} }
EcmascriptModuleCanonicalization::FollowReexports(part) => { EcmascriptModuleCanonicalization::FollowReexports(part) => {
if *module.get_exports().split_locals_and_reexports().await? { let mangle_via_materialized_namespace_object = module
.options()
.await?
.mangle_via_materialized_namespace_object;
if *module
.get_exports()
.split_locals_and_reexports(mangle_via_materialized_namespace_object)
.await?
{
if let Some(part) = part { if let Some(part) = part {
match part { match part {
ModulePart::Evaluation => { ModulePart::Evaluation => {
......
...@@ -281,6 +281,8 @@ struct TestOptions { ...@@ -281,6 +281,8 @@ struct TestOptions {
#[serde(default = "default_true")] #[serde(default = "default_true")]
mangle_export_names: bool, mangle_export_names: bool,
#[serde(default = "default_true")] #[serde(default = "default_true")]
mangle_via_materialized_namespace_object: bool,
#[serde(default = "default_true")]
cross_module_constants: bool, cross_module_constants: bool,
#[serde(default)] #[serde(default)]
cjs_scope_hoisting: bool, cjs_scope_hoisting: bool,
...@@ -319,6 +321,7 @@ impl Default for TestOptions { ...@@ -319,6 +321,7 @@ impl Default for TestOptions {
scope_hoisting: default_true(), scope_hoisting: default_true(),
cjs_tree_shaking: false, cjs_tree_shaking: false,
mangle_export_names: default_true(), mangle_export_names: default_true(),
mangle_via_materialized_namespace_object: default_true(),
cjs_scope_hoisting: false, cjs_scope_hoisting: false,
cross_module_constants: true, cross_module_constants: true,
infer_module_side_effects: default_true(), infer_module_side_effects: default_true(),
...@@ -489,6 +492,8 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -489,6 +492,8 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
enable_exports_info_inlining: true, enable_exports_info_inlining: true,
cjs_tree_shaking: options.cjs_tree_shaking, cjs_tree_shaking: options.cjs_tree_shaking,
mangle_export_names: options.mangle_export_names, mangle_export_names: options.mangle_export_names,
mangle_via_materialized_namespace_object: options
.mangle_via_materialized_namespace_object,
cjs_scope_hoisting: options.cjs_scope_hoisting, cjs_scope_hoisting: options.cjs_scope_hoisting,
cross_module_constants: options.cross_module_constants, cross_module_constants: options.cross_module_constants,
infer_module_side_effects: options.infer_module_side_effects, infer_module_side_effects: options.infer_module_side_effects,
......
...@@ -33,11 +33,10 @@ it('exported lets are live', () => { ...@@ -33,11 +33,10 @@ it('exported lets are live', () => {
}) })
// Whether a binding is emitted as a plain value or as a getter is decided by the module that // Whether a binding is emitted as a plain value or as a getter is decided by the module that
// *owns* it. A local-only module is no longer split merely for export mangling, so its namespace // *owns* it. Materialized-namespace mangling splits the public facade from its `<locals>` module,
// is the right place to inspect the emitted property descriptors. Look up its exact module ID to // so inspect the latter's descriptors rather than those on the forwarding facade.
// avoid accidentally testing a re-export facade instead of the original module.
function moduleNamespaceOf(fileName) { function moduleNamespaceOf(fileName) {
const suffix = `exports/live/input/${fileName} [test] (ecmascript)` const suffix = `exports/live/input/${fileName} [test] (ecmascript) <locals>`
const id = Array.from(__turbopack_modules__.keys()).find((m) => const id = Array.from(__turbopack_modules__.keys()).find((m) =>
m.endsWith(suffix) m.endsWith(suffix)
) )
......
...@@ -9,8 +9,11 @@ it('should keep a CommonJS consumer of an ESM module working', () => { ...@@ -9,8 +9,11 @@ it('should keep a CommonJS consumer of an ESM module working', () => {
}) })
it('should keep a CommonJS consumer working with original export names', () => { it('should keep a CommonJS consumer working with original export names', () => {
// The `esm.someLongExportName` accesses in `cjs-consumer.js` are user source, so the unsplit // The public facade keeps the original names for user-source `esm.someLongExportName` reads,
// module must keep the original keys on its namespace object. // even though the backing module can mangle its local export keys.
expect(exportsInfo.someLongExportName.canMangle).toBe(false) expect(exportsInfo.someLongExportName.canMangle).toBe(true)
expect(exportsInfo.someLongExportName.mangledName).not.toBe(
'someLongExportName'
)
expect(keys()).toContain('someLongExportName') expect(keys()).toContain('someLongExportName')
}) })
...@@ -22,8 +22,10 @@ it('should handle `default` when destructuring a namespace', () => { ...@@ -22,8 +22,10 @@ it('should handle `default` when destructuring a namespace', () => {
}) })
it('should preserve original names when a namespace binding escapes', () => { it('should preserve original names when a namespace binding escapes', () => {
// Without a facade split, the module keeps its public keys because callers can read the // The public facade exposes original names while the backing module mangles its keys.
// namespace object by its original export names. expect(mod.aVeryLongExportName).toBe('a-value')
expect(mod.exportsInfo.aVeryLongExportName.canMangle).toBe(false) expect(mod.exportsInfo.aVeryLongExportName.canMangle).toBe(true)
expect(mod.exportsInfo.aVeryLongExportName.mangledName).toBeNull() expect(mod.exportsInfo.aVeryLongExportName.mangledName).not.toBe(
'aVeryLongExportName'
)
}) })
...@@ -64,10 +64,12 @@ it('should preserve namespace reads through an export-star forwarding edge', () ...@@ -64,10 +64,12 @@ it('should preserve namespace reads through an export-star forwarding edge', ()
it('should preserve namespace names through a multi-hop diamond', () => { it('should preserve namespace names through a multi-hop diamond', () => {
expect(readMultiHopDiamond()).toEqual(['multi-hop', 'multi-hop']) expect(readMultiHopDiamond()).toEqual(['multi-hop', 'multi-hop'])
// Without a mangling-only facade, the escaped namespace and named consumers use the original // The backing module can mangle its local keys, while the escaped facade retains the
// export keys from the same source module. // original public export names for consumers of the namespace.
expect(multiHopExportsInfo.veryLongMultiHopExportName.canMangle).toBe(false) expect(multiHopExportsInfo.veryLongMultiHopExportName.canMangle).toBe(true)
expect(multiHopExportsInfo.veryLongMultiHopExportName.mangledName).toBeNull() expect(multiHopExportsInfo.veryLongMultiHopExportName.mangledName).not.toBe(
'veryLongMultiHopExportName'
)
// The escaped namespace must still expose the ORIGINAL names, both by enumeration and by // The escaped namespace must still expose the ORIGINAL names, both by enumeration and by
// dynamic (non-statically-analyzable) key access. // dynamic (non-statically-analyzable) key access.
expect(enumerateMultiHopNamespace()).toEqual([ expect(enumerateMultiHopNamespace()).toEqual([
......
...@@ -3,10 +3,10 @@ it('should preserve names for a module imported with webpackExports', async () = ...@@ -3,10 +3,10 @@ it('should preserve names for a module imported with webpackExports', async () =
/* webpackExports: ["usedName", "exportsInfo"] */ './lazy' /* webpackExports: ["usedName", "exportsInfo"] */ './lazy'
) )
expect(usedName).toBe('used') expect(usedName).toBe('used')
// The comment narrows which exports are used, but the promise still exposes a namespace // The comment narrows which exports are used, but the promise still exposes the public
// object with the original names. Without a facade, the target cannot mangle those keys. // namespace with original names. The backing module may mangle its local keys.
expect(exportsInfo.usedName.canMangle).toBe(false) expect(exportsInfo.usedName.canMangle).toBe(true)
expect(exportsInfo.usedName.mangledName).toBeNull() expect(exportsInfo.usedName.mangledName).not.toBe('usedName')
}) })
it('should preserve names for a module imported with turbopackExports', async () => { it('should preserve names for a module imported with turbopackExports', async () => {
...@@ -14,12 +14,13 @@ it('should preserve names for a module imported with turbopackExports', async () ...@@ -14,12 +14,13 @@ it('should preserve names for a module imported with turbopackExports', async ()
/* turbopackExports: ["otherUsedName", "exportsInfo"] */ './lazy' /* turbopackExports: ["otherUsedName", "exportsInfo"] */ './lazy'
) )
expect(ns.otherUsedName).toBe('other-used') expect(ns.otherUsedName).toBe('other-used')
expect(ns.exportsInfo.otherUsedName.canMangle).toBe(false) expect(ns.exportsInfo.otherUsedName.canMangle).toBe(true)
expect(ns.exportsInfo.otherUsedName.mangledName).not.toBe('otherUsedName')
}) })
it('should keep a plain dynamic import working', async () => { it('should keep a plain dynamic import working', async () => {
const ns = await import('./lazy') const ns = await import('./lazy')
expect(ns.usedName).toBe('used') expect(ns.usedName).toBe('used')
// The unsplit namespace object still exposes the original names. // The public namespace still exposes the original names.
expect(Object.keys(ns)).toContain('usedName') expect(Object.keys(ns)).toContain('usedName')
}) })
...@@ -31,12 +31,14 @@ it('should keep all 60 values correct through the mangled keys', () => { ...@@ -31,12 +31,14 @@ it('should keep all 60 values correct through the mangled keys', () => {
expect(values()).toEqual(expected) expect(values()).toEqual(expected)
}) })
it('should keep computed-key namespace reads working without mangling', () => { it('should keep computed-key namespace reads working through a facade', () => {
for (let i = 0; i < 60; i++) { for (let i = 0; i < 60; i++) {
const n = String(i).padStart(2, '0') const n = String(i).padStart(2, '0')
expect(manyAsNamespace[`exportNumber${n}`]).toBe(`value-${n}`) expect(manyAsNamespace[`exportNumber${n}`]).toBe(`value-${n}`)
} }
// The namespace-imported module keeps its public names; the separate named-only module // The public namespace retains original keys while its backing module can mangle them.
// checked above remains eligible for mangling. expect(manyAsNamespace.exportsInfo.exportNumber00.canMangle).toBe(true)
expect(manyAsNamespace.exportsInfo.exportNumber00.canMangle).toBe(false) expect(manyAsNamespace.exportsInfo.exportNumber00.mangledName).not.toBe(
'exportNumber00'
)
}) })
export const veryLongExportName = { marker: 'shared' }
export const exportsInfo = __webpack_exports_info__.veryLongExportName
import { veryLongExportName, exportsInfo } from './enums'
it('does not split when only materialized mangling is enabled', async () => {
const dynamic = await import('./enums')
const moduleName =
'exports/mangle-materialized-namespace-no-mangling/input/enums.js [test] (ecmascript)'
const parts = Array.from(__turbopack_modules__.keys())
.filter((id) => id.includes(moduleName))
.map((id) => id.slice(id.indexOf(moduleName)))
expect(parts).toEqual([moduleName])
expect(dynamic.veryLongExportName).toBe(veryLongExportName)
expect(dynamic.exportsInfo).toBe(exportsInfo)
expect(exportsInfo.canMangle).toBe(false)
})
export const ENUM_A = 'a-value'
export const ENUM_B = 'b-value'
export default 'default-value'
export const exportsInfo = {
ENUM_A: __webpack_exports_info__.ENUM_A,
ENUM_B: __webpack_exports_info__.ENUM_B,
}
// Exercise the execution harness's default-on materialized namespace option.
import { ENUM_A, exportsInfo } from './enums'
import { getEnums } from './provider'
it('materializes the public namespace while mangling local export keys', async () => {
const staticNamespace = getEnums()
const dynamicNamespace = await import('./enums')
const moduleName =
'exports/mangle-materialized-namespace-opt-in/input/enums.js [test] (ecmascript)'
const parts = Array.from(__turbopack_modules__.keys())
.filter((id) => id.includes(moduleName))
.map((id) => id.slice(id.indexOf(moduleName)))
.sort()
expect(parts).toEqual([moduleName, `${moduleName} <locals>`])
expect(dynamicNamespace).toBe(staticNamespace)
expect(dynamicNamespace.ENUM_A).toBe(ENUM_A)
expect(dynamicNamespace.exportsInfo).toBe(exportsInfo)
expect(Object.keys(dynamicNamespace).sort()).toEqual([
'ENUM_A',
'ENUM_B',
'default',
'exportsInfo',
])
expect(exportsInfo.ENUM_A.canMangle).toBe(true)
expect(exportsInfo.ENUM_A.mangledName).not.toBe('ENUM_A')
expect(exportsInfo.ENUM_B.mangledName).not.toBe(
exportsInfo.ENUM_A.mangledName
)
})
import * as ns from './enums'
// The namespace object escapes, so the facade has to expose the original names.
export const getEnums = () => ns
// A local-only module should keep one identity when its namespace escapes: splitting it merely // Explicitly opt out of materialized-namespace mangling to retain one module identity for
// for export mangling makes a dynamic import target a facade while named imports use locals. // mixed dynamic and static imports. The public namespace still exposes the original names.
// The public namespace must still expose the original export names.
import { ENUM_A, exportsInfo } from './enums' import { ENUM_A, exportsInfo } from './enums'
import { getEnums } from './provider' import { getEnums } from './provider'
......
{ {
"mangleExportNames": true, "mangleExportNames": true,
"mangleViaMaterializedNamespaceObject": false,
"minify": true, "minify": true,
"scopeHoisting": false "scopeHoisting": false
} }
...@@ -247,6 +247,7 @@ impl ModuleOptions { ...@@ -247,6 +247,7 @@ impl ModuleOptions {
infer_module_side_effects, infer_module_side_effects,
cjs_tree_shaking, cjs_tree_shaking,
mangle_export_names, mangle_export_names,
mangle_via_materialized_namespace_object,
cjs_scope_hoisting, cjs_scope_hoisting,
cross_module_constants, cross_module_constants,
lazy_compilation, lazy_compilation,
...@@ -345,6 +346,7 @@ impl ModuleOptions { ...@@ -345,6 +346,7 @@ impl ModuleOptions {
infer_module_side_effects, infer_module_side_effects,
cjs_tree_shaking, cjs_tree_shaking,
mangle_export_names, mangle_export_names,
mangle_via_materialized_namespace_object,
cjs_scope_hoisting, cjs_scope_hoisting,
cross_module_constants, cross_module_constants,
lazy_compilation, lazy_compilation,
......
...@@ -292,6 +292,9 @@ pub struct EcmascriptOptionsContext { ...@@ -292,6 +292,9 @@ pub struct EcmascriptOptionsContext {
/// is observable from user code — modules whose export names can escape keep their original /// is observable from user code — modules whose export names can escape keep their original
/// names. Defaults to false. /// names. Defaults to false.
pub mangle_export_names: bool, pub mangle_export_names: bool,
/// Whether to materialize public namespaces with a facade so local export keys can still be
/// mangled when the namespace escapes. Defaults to false and requires `mangle_export_names`.
pub mangle_via_materialized_namespace_object: bool,
/// Whether to scope-hoist static CommonJS modules. Defaults to false. /// Whether to scope-hoist static CommonJS modules. Defaults to false.
pub cjs_scope_hoisting: bool, pub cjs_scope_hoisting: bool,
......
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