Skip to content

feat: inline const for leaf modules #10451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jun 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ rustc-hash = { version = "2.1.0" }
scopeguard = "1.2.0"
serde = { version = "1.0.217" }
serde_json = { version = "1.0.134" }
sftrace-setup = { version = "0.1.0" }
sha2 = { version = "0.10.8" }
simd-json = { version = "0.14.3" }
smol_str = { version = "0.3.0" }
Expand All @@ -87,7 +88,6 @@ url = { version = "2.5.4" }
urlencoding = { version = "2.1.3" }
ustr = { package = "ustr-fxhash", version = "1.0.1" }
xxhash-rust = { version = "0.8.14" }
sftrace-setup = { version = "0.1.0" }

# Pinned
napi = { version = "3.0.0-beta.8" }
Expand Down
4 changes: 2 additions & 2 deletions crates/node_binding/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ tokio = { workspace = true, features = ["rt", "
ustr = { workspace = true }

[target.'cfg(not(target_family = "wasm"))'.dependencies]
tokio = { workspace = true, features = ["parking_lot"] }
rspack_tracing = { workspace = true }
sftrace-setup = { workspace = true, optional = true }
sftrace-setup = { workspace = true, optional = true }
tokio = { workspace = true, features = ["parking_lot"] }

[build-dependencies]
napi-build = { workspace = true }
8 changes: 7 additions & 1 deletion crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1059,7 +1059,7 @@ export interface JsRsdoctorModule {
belongModules: Array<number>
chunks: Array<number>
issuerPath: Array<number>
bailoutReason?: string
bailoutReason: Array<string>
}

export interface JsRsdoctorModuleGraph {
Expand Down Expand Up @@ -1885,6 +1885,7 @@ parallelCodeSplitting: boolean
rspackFuture?: RawRspackFuture
cache: boolean | { type: "persistent" } & RawExperimentCacheOptionsPersistent | { type: "memory" }
useInputFileSystem?: false | Array<RegExp>
inlineConst: boolean
}

export interface RawExperimentSnapshotOptions {
Expand Down Expand Up @@ -2094,6 +2095,11 @@ export interface RawJavascriptParserOptions {
* @experimental
*/
importDynamic?: boolean
/**
* This option is experimental in Rspack only and subject to change or be removed anytime.
* @experimental
*/
inlineConst?: boolean
}

export interface RawJsonGeneratorOptions {
Expand Down
2 changes: 2 additions & 0 deletions crates/node_binding/src/raw_options/raw_experiments/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub struct RawExperiments {
pub cache: RawExperimentCacheOptions,
#[napi(ts_type = "false | Array<RegExp>")]
pub use_input_file_system: Option<WithFalse<Vec<RspackRegex>>>,
pub inline_const: bool,
}

impl From<RawExperiments> for Experiments {
Expand All @@ -43,6 +44,7 @@ impl From<RawExperiments> for Experiments {
top_level_await: value.top_level_await,
rspack_future: value.rspack_future.unwrap_or_default().into(),
cache: normalize_raw_experiment_cache_options(value.cache),
inline_const: value.inline_const,
}
}
}
4 changes: 4 additions & 0 deletions crates/node_binding/src/raw_options/raw_module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,9 @@ pub struct RawJavascriptParserOptions {
/// This option is experimental in Rspack only and subject to change or be removed anytime.
/// @experimental
pub import_dynamic: Option<bool>,
/// This option is experimental in Rspack only and subject to change or be removed anytime.
/// @experimental
pub inline_const: Option<bool>,
}

impl From<RawJavascriptParserOptions> for JavascriptParserOptions {
Expand Down Expand Up @@ -329,6 +332,7 @@ impl From<RawJavascriptParserOptions> for JavascriptParserOptions {
require_dynamic: value.require_dynamic,
require_resolve: value.require_resolve,
import_dynamic: value.import_dynamic,
inline_const: value.inline_const,
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions crates/rspack/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1712,6 +1712,7 @@ impl ModuleOptionsBuilder {
require_dynamic: Some(true),
require_resolve: Some(true),
import_dynamic: Some(true),
inline_const: Some(false),
..Default::default()
}),
);
Expand Down Expand Up @@ -3667,6 +3668,8 @@ pub struct ExperimentsBuilder {
parallel_code_splitting: Option<bool>,
/// Whether to enable async web assembly.
async_web_assembly: Option<bool>,
/// Whether to enable inline constants.
inline_const: Option<bool>,
// TODO: lazy compilation
}

Expand All @@ -3683,6 +3686,7 @@ impl From<Experiments> for ExperimentsBuilder {
future_defaults: None,
css: None,
async_web_assembly: None,
inline_const: Some(value.inline_const),
}
}
}
Expand All @@ -3700,6 +3704,7 @@ impl From<&mut ExperimentsBuilder> for ExperimentsBuilder {
css: value.css.take(),
parallel_code_splitting: value.parallel_code_splitting.take(),
async_web_assembly: value.async_web_assembly.take(),
inline_const: value.inline_const.take(),
}
}
}
Expand Down Expand Up @@ -3791,6 +3796,7 @@ impl ExperimentsBuilder {
w!(self.output_module, false);

let parallel_code_splitting = d!(self.parallel_code_splitting, false);
let inline_const = d!(self.inline_const, production);

Ok(Experiments {
layers,
Expand All @@ -3799,6 +3805,7 @@ impl ExperimentsBuilder {
rspack_future,
parallel_code_splitting,
cache,
inline_const,
})
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1417,6 +1417,9 @@ CompilerOptions {
import_dynamic: Some(
true,
),
inline_const: Some(
false,
),
},
),
},
Expand Down Expand Up @@ -1453,6 +1456,7 @@ CompilerOptions {
top_level_await: true,
rspack_future: RspackFuture,
cache: Disabled,
inline_const: false,
},
node: Some(
NodeOption {
Expand Down
150 changes: 104 additions & 46 deletions crates/rspack_core/src/concatenated_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ use crate::{
define_es_module_flag_statement, filter_runtime, impl_source_map_config, merge_runtime_condition,
merge_runtime_condition_non_false, module_update_hash, property_access, property_name,
reserved_names::RESERVED_NAMES, returning_function, runtime_condition_expression,
subtract_runtime_condition, to_identifier, AsyncDependenciesBlockIdentifier, BoxDependency,
BoxDependencyTemplate, BoxModuleDependency, BuildContext, BuildInfo, BuildMeta,
subtract_runtime_condition, to_identifier, to_normal_comment, AsyncDependenciesBlockIdentifier,
BoxDependency, BoxDependencyTemplate, BoxModuleDependency, BuildContext, BuildInfo, BuildMeta,
BuildMetaDefaultObject, BuildMetaExportsType, BuildResult, ChunkGraph, ChunkInitFragments,
ChunkRenderContext, CodeGenerationDataTopLevelDeclarations, CodeGenerationExportsFinalNames,
CodeGenerationPublicPathAutoReplace, CodeGenerationResult, Compilation, ConcatenatedModuleIdent,
Expand All @@ -53,7 +53,7 @@ use crate::{
LibIdentOptions, MaybeDynamicTargetExportInfoHashKey, Module, ModuleArgument, ModuleGraph,
ModuleGraphCacheArtifact, ModuleGraphConnection, ModuleIdentifier, ModuleLayer, ModuleType,
PrefetchExportsInfoMode, Resolve, RuntimeCondition, RuntimeGlobals, RuntimeSpec, SourceType,
SpanExt, Template, UsageState, DEFAULT_EXPORT, NAMESPACE_OBJECT_EXPORT,
SpanExt, UsageState, UsedName, UsedNameItem, DEFAULT_EXPORT, NAMESPACE_OBJECT_EXPORT,
};

type ExportsDefinitionArgs = Vec<(String, String)>;
Expand Down Expand Up @@ -991,6 +991,7 @@ impl Module for ConcatenatedModule {

let mut exports_map: HashMap<Atom, String> = HashMap::default();
let mut unused_exports: HashSet<Atom> = HashSet::default();
let mut inlined_exports: HashSet<Atom> = HashSet::default();

let root_info = module_to_info_map
.get(&self.root_module_ctxt.id)
Expand Down Expand Up @@ -1021,6 +1022,10 @@ impl Module for ConcatenatedModule {
unused_exports.insert(name);
continue;
};
let UsedNameItem::Str(used_name) = used_name else {
inlined_exports.insert(name);
continue;
};
exports_map.insert(used_name.clone(), {
let final_name = Self::get_final_name(
&compilation.get_module_graph(),
Expand Down Expand Up @@ -1164,6 +1169,13 @@ impl Module for ConcatenatedModule {
join_atom(unused_exports.iter(), ", ")
)));
}
// List inlined exports
if !inlined_exports.is_empty() {
result.add(RawStringSource::from(format!(
"\n// INLINED EXPORTS: {}\n",
join_atom(inlined_exports.iter(), ", ")
)));
}

let mut namespace_object_sources: IdentifierMap<String> = IdentifierMap::default();

Expand Down Expand Up @@ -1210,7 +1222,7 @@ impl Module for ConcatenatedModule {
continue;
}

if let Some(used_name) =
if let Some(UsedNameItem::Str(used_name)) =
ExportInfoGetter::get_used_name(export_info.as_data(&module_graph), None, runtime)
{
let final_name = Self::get_final_name(
Expand Down Expand Up @@ -2256,16 +2268,36 @@ impl ConcatenatedModule {
if let Some(used_name) =
ExportsInfoGetter::get_used_name(&exports_info, runtime, &export_name)
{
// https://github.com/webpack/webpack/blob/1f99ad6367f2b8a6ef17cce0e058f7a67fb7db18/lib/optimize/ConcatenatedModule.js#L402-L404
let used_name = used_name.to_used_name_vec();

return Binding::Symbol(SymbolBinding {
info_id: info.module,
name: direct_export.as_str().into(),
ids: used_name[1..].to_vec(),
export_name,
comment: None,
});
match used_name {
UsedName::Normal(used_name) => {
// https://github.com/webpack/webpack/blob/1f99ad6367f2b8a6ef17cce0e058f7a67fb7db18/lib/optimize/ConcatenatedModule.js#L402-L404
return Binding::Symbol(SymbolBinding {
info_id: info.module,
name: direct_export.as_str().into(),
ids: used_name[1..].to_vec(),
export_name,
comment: None,
});
}
UsedName::Inlined(inlined) => {
return Binding::Raw(RawBinding {
raw_name: format!(
"{} {}",
to_normal_comment(&format!(
"inlined export {}",
property_access(&export_name, 0)
)),
inlined.render()
)
.into(),
// Inlined export is definitely a terminal binding
ids: vec![],
export_name,
info_id: info.module,
comment: None,
});
}
}
} else {
return Binding::Raw(RawBinding {
raw_name: "/* unused export */ undefined".into(),
Expand Down Expand Up @@ -2335,20 +2367,29 @@ impl ConcatenatedModule {
// That's how webpack write https://github.com/webpack/webpack/blob/1f99ad6367f2b8a6ef17cce0e058f7a67fb7db18/lib/optimize/ConcatenatedModule.js#L463-L471
let used_name = ExportsInfoGetter::get_used_name(&exports_info, runtime, &export_name)
.expect("should have export name");

let used_name = used_name.to_used_name_vec();
return Binding::Raw(RawBinding {
info_id: info.module,
raw_name: info
.namespace_object_name
.as_ref()
.expect("should have raw name")
.as_str()
.into(),
ids: used_name,
export_name,
comment: None,
});
return match used_name {
UsedName::Normal(used_name) => Binding::Raw(RawBinding {
info_id: info.module,
raw_name: info
.namespace_object_name
.as_ref()
.expect("should have raw name")
.as_str()
.into(),
ids: used_name,
export_name,
comment: None,
}),
// Inlined namespace export symbol is not possible for now but we compat it here
UsedName::Inlined(inlined) => Binding::Raw(RawBinding {
info_id: info.module,
raw_name: inlined.render().into(),
// Inlined export is definitely a terminal binding
ids: vec![],
export_name,
comment: None,
}),
};
}

panic!(
Expand All @@ -2361,24 +2402,41 @@ impl ConcatenatedModule {
if let Some(used_name) =
ExportsInfoGetter::get_used_name(&exports_info, runtime, &export_name)
{
let used_name = used_name.to_used_name_vec();
let comment = if used_name == export_name {
String::new()
} else {
Template::to_normal_comment(&join_atom(export_name.iter(), ","))
};
Binding::Raw(RawBinding {
raw_name: format!(
"{}{}",
info.name.as_ref().expect("should have name"),
comment
)
.into(),
ids: used_name,
export_name,
info_id: info.module,
comment: None,
})
match used_name {
UsedName::Normal(used_name) => {
let comment = if used_name == export_name {
String::new()
} else {
to_normal_comment(&property_access(&export_name, 0))
};
Binding::Raw(RawBinding {
raw_name: format!(
"{}{}",
info.name.as_ref().expect("should have name"),
comment
)
.into(),
ids: used_name,
export_name,
info_id: info.module,
comment: None,
})
}
UsedName::Inlined(inlined) => {
let comment = to_normal_comment(&format!(
"inlined export {}",
property_access(&export_name, 0)
));
Binding::Raw(RawBinding {
raw_name: format!("{}{}", inlined.render(), comment).into(),
// Inlined export is definitely a terminal binding
ids: vec![],
export_name,
info_id: info.module,
comment: None,
})
}
}
} else {
Binding::Raw(RawBinding {
raw_name: "/* unused export */ undefined".into(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,11 @@ impl Dependency for ContextElementDependency {
referenced_exports
.iter()
.map(|export| {
ExtendedReferencedExport::Export(ReferencedExport::new(vec![export.clone()], false))
ExtendedReferencedExport::Export(ReferencedExport::new(
vec![export.clone()],
false,
false,
))
})
.collect_vec()
} else {
Expand Down
Loading
Loading