diff --git a/crates/rspack_binding_api/src/plugins/interceptor.rs b/crates/rspack_binding_api/src/plugins/interceptor.rs index 5d4360e20dae..2e306d224dec 100644 --- a/crates/rspack_binding_api/src/plugins/interceptor.rs +++ b/crates/rspack_binding_api/src/plugins/interceptor.rs @@ -1481,12 +1481,19 @@ impl CompilationRuntimeModule for CompilationRuntimeModuleTap { let Some(module) = runtime_modules.get(m) else { return Ok(()); }; - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); let context = RuntimeModuleGenerateContext { compilation, runtime_template: &runtime_template, }; let source_string = module.generate(&context).await?; + let runtime_module_prefix = if compilation.runtime_template.render_mode().is_legacy() { + "webpack/runtime/" + } else { + "rspack/runtime/" + }; let arg = JsRuntimeModuleArg { module: JsRuntimeModule { source: Some(JsSourceToJs::from(source_string)), @@ -1495,7 +1502,7 @@ impl CompilationRuntimeModule for CompilationRuntimeModuleTap { name: module .name() .as_str() - .cow_replace(compilation.runtime_template.runtime_module_prefix(), "") + .cow_replace(runtime_module_prefix, "") .into_owned(), stage: module.stage().into(), isolate: module.should_isolate(compilation.options.experiments.runtime_mode), diff --git a/crates/rspack_core/src/options/experiments/mod.rs b/crates/rspack_core/src/options/experiments/mod.rs index e5473d1c5145..10f5e0181429 100644 --- a/crates/rspack_core/src/options/experiments/mod.rs +++ b/crates/rspack_core/src/options/experiments/mod.rs @@ -19,12 +19,6 @@ pub mod runtime_mode { } } } - - impl RuntimeMode { - pub fn uses_runtime_context(&self) -> bool { - matches!(self, RuntimeMode::Rspack) - } - } } use runtime_mode::RuntimeMode; diff --git a/crates/rspack_core/src/runtime_globals.rs b/crates/rspack_core/src/runtime_globals.rs index c96ef5312a80..016e6eae8047 100644 --- a/crates/rspack_core/src/runtime_globals.rs +++ b/crates/rspack_core/src/runtime_globals.rs @@ -5,8 +5,6 @@ use heck::ToLowerCamelCase; use rspack_hash::{RspackHash, RspackHasher}; use rustc_hash::FxHashMap; -use crate::{CompilerOptions, runtime_mode::RuntimeMode}; - #[rspack_cacheable::cacheable] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub struct RuntimeGlobals(u128); @@ -498,16 +496,6 @@ pub enum RuntimeVariable { StartupExec, } -pub fn runtime_variable_to_string( - runtime_variable: &RuntimeVariable, - compiler_options: &CompilerOptions, -) -> String { - match compiler_options.experiments.runtime_mode { - RuntimeMode::Webpack => runtime_variable_name(runtime_variable).to_string(), - RuntimeMode::Rspack => rspack_runtime_variable_name(runtime_variable).to_string(), - } -} - pub fn rspack_runtime_variable_name(runtime_variable: &RuntimeVariable) -> &'static str { match *runtime_variable { RuntimeVariable::Require => "__rspack_require", diff --git a/crates/rspack_core/src/runtime_module.rs b/crates/rspack_core/src/runtime_module.rs index 81fa5b96af36..5200b3150f95 100644 --- a/crates/rspack_core/src/runtime_module.rs +++ b/crates/rspack_core/src/runtime_module.rs @@ -21,7 +21,7 @@ use crate::{ pub struct RuntimeModuleGenerateContext<'a> { pub compilation: &'a Compilation, - pub runtime_template: &'a RuntimeCodeTemplate<'a>, + pub runtime_template: &'a RuntimeCodeTemplate, } pub fn runtime_module_owned_define_fields( @@ -168,7 +168,9 @@ pub async fn runtime_module_get_generated_code( let result: Result<&BoxSource> = common .cached_generated_code .get_or_try_init(|| async { - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); let context = RuntimeModuleGenerateContext { compilation, runtime_template: &runtime_template, @@ -207,7 +209,9 @@ pub async fn runtime_module_get_runtime_hash( module.name().hash(&mut hasher); module.stage().hash(&mut hasher); if module.full_hash() || module.dependent_hash() { - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); let context = RuntimeModuleGenerateContext { compilation, runtime_template: &runtime_template, diff --git a/crates/rspack_core/src/runtime_template.rs b/crates/rspack_core/src/runtime_template.rs index 51f78eed5b65..961b930eda55 100644 --- a/crates/rspack_core/src/runtime_template.rs +++ b/crates/rspack_core/src/runtime_template.rs @@ -26,8 +26,7 @@ use crate::{ RuntimeCondition, RuntimeGlobals, RuntimeSpec, UsedName, compile_boolean_matcher_from_lists, contextify, property_access, runtime_globals::{ - RuntimeVariable, rspack_runtime_variable_name, runtime_globals_to_string, - runtime_variable_name, runtime_variable_to_string, + RuntimeVariable, rspack_runtime_variable_name, runtime_globals_to_string, runtime_variable_name, }, runtime_mode::RuntimeMode, to_comment, to_normal_comment, @@ -35,10 +34,8 @@ use crate::{ pub struct RuntimeTemplate { compiler_options: Arc, - runtime_mode: RuntimeMode, - runtime_globals: Arc, - module_runtime_globals: Arc, - dojang: Option, + render_mode: RuntimeTemplateRenderMode, + dojang: Arc, } static RUNTIME_GLOBALS_PATTERN: LazyLock = @@ -46,29 +43,100 @@ static RUNTIME_GLOBALS_PATTERN: LazyLock = static WEBPACK_RUNTIME_GLOBALS: LazyLock> = LazyLock::new(|| { Arc::new(runtime_globals_to_render_map( - RuntimeGlobalRenderMode::Webpack, + RuntimeGlobalsRenderMode::Webpack, )) }); -static RSPACK_MODULE_RUNTIME_GLOBALS: LazyLock> = +static RSPACK_CONTEXT_RUNTIME_GLOBALS: LazyLock> = LazyLock::new(|| { Arc::new(runtime_globals_to_render_map( - RuntimeGlobalRenderMode::RspackModule, + RuntimeGlobalsRenderMode::RspackContext, )) }); -static RSPACK_RUNTIME_GLOBALS: LazyLock> = LazyLock::new(|| { - Arc::new(runtime_globals_to_render_map( - RuntimeGlobalRenderMode::RspackRuntimeModule, - )) -}); +static RSPACK_LEXICAL_RUNTIME_GLOBALS: LazyLock> = + LazyLock::new(|| { + Arc::new(runtime_globals_to_render_map( + RuntimeGlobalsRenderMode::RspackLexical, + )) + }); + +/// Controls how a single runtime global is rendered into its final JavaScript identifier. +#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)] +pub enum RuntimeGlobalsRenderMode { + /// Renders webpack-compatible identifiers such as `__webpack_require__.d`. + #[default] + Webpack, + /// Renders runtime globals as properties on `__rspack_context`. + RspackContext, + /// Renders runtime globals as lexical variables such as `definePropertyGetters`. + RspackLexical, +} + +impl RuntimeGlobalsRenderMode { + /// Returns whether runtime globals use webpack-compatible identifiers. + pub fn is_legacy(self) -> bool { + matches!(self, Self::Webpack) + } + fn render_runtime_variable(self, runtime_variable: &RuntimeVariable) -> String { + match self { + Self::Webpack => runtime_variable_name(runtime_variable).to_string(), + Self::RspackContext | Self::RspackLexical => { + rspack_runtime_variable_name(runtime_variable).to_string() + } + } + } +} + +/// Selects the runtime-global representation used by each code-template scenario. #[derive(Debug, Clone, Copy, Default, Eq, PartialEq)] -pub enum RuntimeGlobalRenderMode { +pub enum RuntimeTemplateRenderMode { + /// Uses webpack-compatible runtime globals in every code-template scenario. #[default] Webpack, - RspackModule, - RspackRuntimeModule, + /// Uses context references in modules and chunks, and lexical bindings in runtime modules. + Rspack, +} + +impl RuntimeTemplateRenderMode { + /// Returns whether all runtime globals use webpack-compatible identifiers. + pub fn is_legacy(self) -> bool { + matches!(self, Self::Webpack) + } + + /// Returns the runtime-global render mode for ordinary module code generation. + pub fn module_render_mode(self) -> RuntimeGlobalsRenderMode { + match self { + Self::Webpack => RuntimeGlobalsRenderMode::Webpack, + Self::Rspack => RuntimeGlobalsRenderMode::RspackContext, + } + } + + /// Returns the runtime-global render mode used to generate runtime modules. + pub fn runtime_module_render_mode(self) -> RuntimeGlobalsRenderMode { + match self { + Self::Webpack => RuntimeGlobalsRenderMode::Webpack, + Self::Rspack => RuntimeGlobalsRenderMode::RspackLexical, + } + } + + /// Returns the runtime-global render mode used while assembling final chunks. + pub fn chunk_render_mode(self) -> RuntimeGlobalsRenderMode { + match self { + Self::Webpack => RuntimeGlobalsRenderMode::Webpack, + Self::Rspack => RuntimeGlobalsRenderMode::RspackContext, + } + } +} + +impl From for RuntimeTemplateRenderMode { + fn from(value: RuntimeMode) -> Self { + match value { + RuntimeMode::Webpack => Self::Webpack, + RuntimeMode::Rspack => Self::Rspack, + } + } } #[derive(Debug)] @@ -110,9 +178,8 @@ impl Debug for RuntimeTemplate { impl RuntimeTemplate { pub fn new(compiler_options: Arc) -> Self { - let runtime_mode = compiler_options.experiments.runtime_mode; - let runtime_globals = get_runtime_globals_render_map(runtime_mode.runtime_render_mode()); - let module_runtime_globals = get_runtime_globals_render_map(runtime_mode.module_render_mode()); + let render_mode = RuntimeTemplateRenderMode::from(compiler_options.experiments.runtime_mode); + let runtime_globals = get_runtime_globals_render_map(render_mode.runtime_module_render_mode()); let mut dojang = Dojang::new(); let runtime_globals_cloned = runtime_globals.clone(); @@ -175,15 +242,19 @@ impl RuntimeTemplate { ); let runtime_globals_cloned = runtime_globals.clone(); - let runtime_mode_cloned = runtime_mode; + let runtime_globals_render_mode = render_mode.runtime_module_render_mode(); dojang.functions.insert( "define".into(), FunctionContainer::F1(Box::new(move |runtime_global: Operand| { - dojang_define(runtime_global, &runtime_globals_cloned, runtime_mode_cloned) + dojang_define( + runtime_global, + &runtime_globals_cloned, + runtime_globals_render_mode, + ) })), ); - let runtime_globals_cloned = runtime_globals.clone(); + let runtime_globals_cloned = runtime_globals; dojang.functions.insert( "weak".into(), FunctionContainer::F1(Box::new(move |runtime_global: Operand| { @@ -193,16 +264,15 @@ impl RuntimeTemplate { Self { compiler_options, - runtime_mode, - runtime_globals, - module_runtime_globals, - dojang: Some(dojang), + render_mode, + dojang: Arc::new(dojang), } } pub fn add_templates(&mut self, templates: Vec<(String, String)>) { for (key, template) in templates { - let dojang = self.dojang.as_mut().expect("dojang should be initialized"); + let dojang = Arc::get_mut(&mut self.dojang) + .expect("runtime templates cannot be added while a code template is alive"); if !dojang.templates.contains_key(&key) { dojang .add_with_option(key.clone(), template) @@ -211,11 +281,9 @@ impl RuntimeTemplate { } } - pub fn runtime_module_prefix(&self) -> &'static str { - match self.runtime_mode { - RuntimeMode::Webpack => "webpack/runtime/", - RuntimeMode::Rspack => "rspack/runtime/", - } + /// Returns the render-mode combination selected for this compilation. + pub fn render_mode(&self) -> RuntimeTemplateRenderMode { + self.render_mode } pub fn create_runtime_module_identifier(&self, name: &str) -> Identifier { @@ -224,93 +292,68 @@ impl RuntimeTemplate { } else { name }; - Identifier::from(format!( - "{}{}", - self.runtime_module_prefix(), - module_name.to_snake_case() - )) + self.create_custom_runtime_module_identifier(&module_name.to_snake_case()) } pub fn create_custom_runtime_module_identifier(&self, custom: &str) -> Identifier { - Identifier::from(format!("{}{custom}", self.runtime_module_prefix())) + let prefix = if self.render_mode.is_legacy() { + "webpack/runtime/" + } else { + "rspack/runtime/" + }; + Identifier::from(format!("{prefix}{custom}")) } + /// Creates the template used to render runtime globals referenced by ordinary modules. pub fn create_module_code_template(&self) -> ModuleCodeTemplate { ModuleCodeTemplate::new( self.compiler_options.clone(), - self.module_runtime_globals.clone(), + self.render_mode.module_render_mode(), ) } - pub fn create_runtime_code_template<'a>(&'a self) -> RuntimeCodeTemplate<'a> { + /// Creates the template used by `RuntimeModule::generate` in every generation phase. + pub fn create_runtime_module_code_template(&self) -> RuntimeCodeTemplate { RuntimeCodeTemplate::new( self.compiler_options.clone(), - self.runtime_globals.clone(), - self.dojang.as_ref().expect("dojang should be initialized"), - self.runtime_mode.uses_runtime_context(), - self.runtime_mode == RuntimeMode::Rspack, + self.render_mode.runtime_module_render_mode(), + self.dojang.clone(), ) } - pub fn create_runtime_module_code_template<'a>(&'a self) -> RuntimeCodeTemplate<'a> { + /// Creates the template used to render runtime globals while assembling a chunk. + pub fn create_chunk_code_template(&self) -> RuntimeCodeTemplate { RuntimeCodeTemplate::new( self.compiler_options.clone(), - self.module_runtime_globals.clone(), - self.dojang.as_ref().expect("dojang should be initialized"), - self.runtime_mode.uses_runtime_context(), - self.runtime_mode == RuntimeMode::Rspack, + self.render_mode.chunk_render_mode(), + self.dojang.clone(), ) } - - pub fn create_chunk_code_template(&self) -> ChunkCodeTemplate { - ChunkCodeTemplate::new( - self.compiler_options.clone(), - self.module_runtime_globals.clone(), - self.runtime_mode.uses_runtime_context(), - self.runtime_mode == RuntimeMode::Rspack, - ) - } -} - -impl RuntimeMode { - fn module_render_mode(self) -> RuntimeGlobalRenderMode { - match self { - RuntimeMode::Webpack => RuntimeGlobalRenderMode::Webpack, - RuntimeMode::Rspack => RuntimeGlobalRenderMode::RspackModule, - } - } - - fn runtime_render_mode(self) -> RuntimeGlobalRenderMode { - match self { - RuntimeMode::Webpack => RuntimeGlobalRenderMode::Webpack, - RuntimeMode::Rspack => RuntimeGlobalRenderMode::RspackRuntimeModule, - } - } } fn get_runtime_globals_render_map( - render_mode: RuntimeGlobalRenderMode, + render_mode: RuntimeGlobalsRenderMode, ) -> Arc { match render_mode { - RuntimeGlobalRenderMode::Webpack => WEBPACK_RUNTIME_GLOBALS.clone(), - RuntimeGlobalRenderMode::RspackModule => RSPACK_MODULE_RUNTIME_GLOBALS.clone(), - RuntimeGlobalRenderMode::RspackRuntimeModule => RSPACK_RUNTIME_GLOBALS.clone(), + RuntimeGlobalsRenderMode::Webpack => WEBPACK_RUNTIME_GLOBALS.clone(), + RuntimeGlobalsRenderMode::RspackContext => RSPACK_CONTEXT_RUNTIME_GLOBALS.clone(), + RuntimeGlobalsRenderMode::RspackLexical => RSPACK_LEXICAL_RUNTIME_GLOBALS.clone(), } } -fn runtime_globals_to_render_map(render_mode: RuntimeGlobalRenderMode) -> RuntimeGlobalsRenderMap { +fn runtime_globals_to_render_map(render_mode: RuntimeGlobalsRenderMode) -> RuntimeGlobalsRenderMap { let mut runtime_values = FxHashMap::default(); for (_, runtime_globals) in RuntimeGlobals::all().iter_names() { let rendered = match render_mode { - RuntimeGlobalRenderMode::Webpack => { + RuntimeGlobalsRenderMode::Webpack => { if runtime_globals == RuntimeGlobals::REQUIRE_SCOPE { runtime_variable_name(&RuntimeVariable::Require).to_string() } else { runtime_globals_to_string(&runtime_globals) } } - RuntimeGlobalRenderMode::RspackModule => { + RuntimeGlobalsRenderMode::RspackContext => { if runtime_globals == RuntimeGlobals::REQUIRE_SCOPE { runtime_variable_name(&RuntimeVariable::Context).to_string() } else if runtime_globals == RuntimeGlobals::REQUIRE { @@ -331,7 +374,7 @@ fn runtime_globals_to_render_map(render_mode: RuntimeGlobalRenderMode) -> Runtim runtime_globals_to_string(&runtime_globals) } } - RuntimeGlobalRenderMode::RspackRuntimeModule => { + RuntimeGlobalsRenderMode::RspackLexical => { if runtime_globals == RuntimeGlobals::REQUIRE_SCOPE { runtime_variable_name(&RuntimeVariable::Context).to_string() } else if runtime_globals == RuntimeGlobals::REQUIRE { @@ -518,18 +561,18 @@ fn dojang_array_destructure( fn dojang_define( runtime_global: Operand, runtime_globals: &RuntimeGlobalsRenderMap, - runtime_mode: RuntimeMode, + render_mode: RuntimeGlobalsRenderMode, ) -> Operand { // `define(...)` marks a runtime global assignment; the EJS extractor records it in `define`. - if runtime_mode == RuntimeMode::Rspack { - return Operand::Value(Value::from(format!( + match render_mode { + RuntimeGlobalsRenderMode::RspackLexical => Operand::Value(Value::from(format!( "var {}", to_cow(&runtime_global, runtime_globals) - ))); + ))), + RuntimeGlobalsRenderMode::Webpack | RuntimeGlobalsRenderMode::RspackContext => Operand::Value( + Value::from(to_cow(&runtime_global, runtime_globals).into_owned()), + ), } - Operand::Value(Value::from( - to_cow(&runtime_global, runtime_globals).into_owned(), - )) } fn dojang_weak(runtime_global: Operand, runtime_globals: &RuntimeGlobalsRenderMap) -> Operand { @@ -692,6 +735,7 @@ pub fn get_outgoing_async_modules( #[derive(Debug)] pub struct ModuleCodeTemplate { compiler_options: Arc, + runtime_globals_render_mode: RuntimeGlobalsRenderMode, runtime_globals: Arc, runtime_requirements: RuntimeGlobals, } @@ -699,11 +743,12 @@ pub struct ModuleCodeTemplate { impl ModuleCodeTemplate { fn new( compiler_options: Arc, - runtime_globals: Arc, + runtime_globals_render_mode: RuntimeGlobalsRenderMode, ) -> Self { Self { compiler_options, - runtime_globals, + runtime_globals_render_mode, + runtime_globals: get_runtime_globals_render_map(runtime_globals_render_mode), runtime_requirements: RuntimeGlobals::default(), } } @@ -757,7 +802,14 @@ impl ModuleCodeTemplate { } pub fn render_runtime_variable(&self, runtime_variable: &RuntimeVariable) -> String { - runtime_variable_to_string(runtime_variable, &self.compiler_options) + self + .runtime_globals_render_mode + .render_runtime_variable(runtime_variable) + } + + /// Returns the final runtime-global representation used by this module template. + pub fn render_mode(&self) -> RuntimeGlobalsRenderMode { + self.runtime_globals_render_mode } pub fn returning_function(&self, return_value: &str, args: &str) -> String { @@ -1655,95 +1707,57 @@ return {} } } -struct RuntimeCodeTemplateInner<'a> { +/// Renders runtime globals for both runtime-module generation and chunk assembly. +pub struct RuntimeCodeTemplate { compiler_options: Arc, + render_mode: RuntimeGlobalsRenderMode, runtime_globals: Arc, - dojang: &'a Dojang, - uses_runtime_context: bool, - uses_lexical_runtime_globals: bool, + dojang: Arc, } -pub struct RuntimeCodeTemplate<'a> { - inner: RuntimeCodeTemplateInner<'a>, -} - -pub struct ChunkCodeTemplate { - compiler_options: Arc, - runtime_globals: Arc, - uses_runtime_context: bool, - uses_lexical_runtime_globals: bool, -} - -impl<'a> RuntimeCodeTemplate<'a> { +impl RuntimeCodeTemplate { fn new( compiler_options: Arc, - runtime_globals: Arc, - dojang: &'a Dojang, - uses_runtime_context: bool, - uses_lexical_runtime_globals: bool, + render_mode: RuntimeGlobalsRenderMode, + dojang: Arc, ) -> Self { Self { - inner: RuntimeCodeTemplateInner { - compiler_options, - runtime_globals, - dojang, - uses_runtime_context, - uses_lexical_runtime_globals, - }, + compiler_options, + render_mode, + runtime_globals: get_runtime_globals_render_map(render_mode), + dojang, } } pub fn render_runtime_global_definition(&self, runtime_globals: &RuntimeGlobals) -> String { - let runtime_global = self.inner.runtime_globals.render(runtime_globals); - if self.inner.uses_lexical_runtime_globals { - format!("var {runtime_global}") - } else { - runtime_global + let runtime_global = self.runtime_globals.render(runtime_globals); + match self.render_mode { + RuntimeGlobalsRenderMode::RspackLexical => format!("var {runtime_global}"), + RuntimeGlobalsRenderMode::Webpack | RuntimeGlobalsRenderMode::RspackContext => runtime_global, } } -} -impl ChunkCodeTemplate { - fn new( - compiler_options: Arc, - runtime_globals: Arc, - uses_runtime_context: bool, - uses_lexical_runtime_globals: bool, - ) -> Self { - Self { - compiler_options, - runtime_globals, - uses_runtime_context, - uses_lexical_runtime_globals, - } + /// Returns the final runtime-global representation selected by the creating factory. + pub fn render_mode(&self) -> RuntimeGlobalsRenderMode { + self.render_mode } -} -impl RuntimeCodeTemplateInner<'_> { pub fn render_runtime_globals(&self, runtime_globals: &RuntimeGlobals) -> String { self.runtime_globals.render(runtime_globals) } pub fn render_runtime_variable(&self, runtime_variable: &RuntimeVariable) -> String { - runtime_variable_to_string(runtime_variable, &self.compiler_options) - } - - pub fn uses_runtime_context(&self) -> bool { - self.uses_runtime_context + self.render_mode.render_runtime_variable(runtime_variable) } pub fn render_runtime_argument(&self) -> String { - if self.uses_runtime_context() { - self.render_runtime_variable(&RuntimeVariable::Context) - } else { + if self.render_mode.is_legacy() { self.render_runtime_globals(&RuntimeGlobals::REQUIRE) + } else { + self.render_runtime_variable(&RuntimeVariable::Context) } } - pub fn uses_lexical_runtime_globals(&self) -> bool { - self.uses_lexical_runtime_globals - } - pub fn render_exports_argument(&self, exports_argument: ExportsArgument) -> String { match exports_argument { ExportsArgument::Exports => "exports".to_string(), @@ -1833,116 +1847,3 @@ impl RuntimeCodeTemplateInner<'_> { } } } - -macro_rules! impl_code_template_methods { - ($ty:ident) => { - impl $ty<'_> { - pub fn render_runtime_globals(&self, runtime_globals: &RuntimeGlobals) -> String { - self.inner.render_runtime_globals(runtime_globals) - } - - pub fn render_runtime_variable(&self, runtime_variable: &RuntimeVariable) -> String { - self.inner.render_runtime_variable(runtime_variable) - } - - pub fn uses_runtime_context(&self) -> bool { - self.inner.uses_runtime_context() - } - - pub fn render_runtime_argument(&self) -> String { - self.inner.render_runtime_argument() - } - - pub fn uses_lexical_runtime_globals(&self) -> bool { - self.inner.uses_lexical_runtime_globals() - } - - pub fn render_exports_argument(&self, exports_argument: ExportsArgument) -> String { - self.inner.render_exports_argument(exports_argument) - } - - pub fn render_module_argument(&self, module_argument: ModuleArgument) -> String { - self.inner.render_module_argument(module_argument) - } - - pub fn render_this_exports(&self) -> String { - self.inner.render_this_exports() - } - - pub fn render(&self, key: &str, params: Option) -> Result { - self.inner.render(key, params) - } - - pub fn basic_function(&self, args: &str, body: &str) -> String { - self.inner.basic_function(args, body) - } - } - }; -} - -impl_code_template_methods!(RuntimeCodeTemplate); - -impl ChunkCodeTemplate { - pub fn render_runtime_globals(&self, runtime_globals: &RuntimeGlobals) -> String { - self.runtime_globals.render(runtime_globals) - } - - pub fn render_runtime_variable(&self, runtime_variable: &RuntimeVariable) -> String { - runtime_variable_to_string(runtime_variable, &self.compiler_options) - } - - pub fn uses_runtime_context(&self) -> bool { - self.uses_runtime_context - } - - pub fn render_runtime_argument(&self) -> String { - if self.uses_runtime_context() { - self.render_runtime_variable(&RuntimeVariable::Context) - } else { - self.render_runtime_globals(&RuntimeGlobals::REQUIRE) - } - } - - pub fn uses_lexical_runtime_globals(&self) -> bool { - self.uses_lexical_runtime_globals - } - - pub fn render_exports_argument(&self, exports_argument: ExportsArgument) -> String { - match exports_argument { - ExportsArgument::Exports => "exports".to_string(), - ExportsArgument::RspackExports => self.render_runtime_variable(&RuntimeVariable::Exports), - } - } - - pub fn render_module_argument(&self, module_argument: ModuleArgument) -> String { - match module_argument { - ModuleArgument::Module => "module".to_string(), - ModuleArgument::RspackModule => self.render_runtime_variable(&RuntimeVariable::Module), - } - } - - pub fn render_this_exports(&self) -> String { - "this".to_string() - } - - pub fn basic_function(&self, args: &str, body: &str) -> String { - if self - .compiler_options - .output - .environment - .supports_arrow_function() - { - format!( - r#"({args}) => {{ -{body} -}}"# - ) - } else { - format!( - r#"function({args}) {{ -{body} -}}"# - ) - } - } -} diff --git a/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs b/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs index 536734e99df7..757d40dd6b2b 100644 --- a/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs +++ b/crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs @@ -515,7 +515,9 @@ async fn render_manifest( .build_chunk_graph_artifact .chunk_by_ukey .expect_get(chunk_ukey); - let _runtime_template = compilation.runtime_template.create_runtime_code_template(); + let _runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); if matches!(chunk.kind(), ChunkKind::HotUpdate) { return Ok(()); } diff --git a/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs b/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs index f59d0294e7ab..faacef4f14bc 100644 --- a/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs +++ b/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs @@ -3,9 +3,9 @@ use std::borrow::Cow; use cow_utils::CowUtils; use derive_more::Debug; use rspack_core::{ - ChunkCodeTemplate, ChunkInitFragments, ChunkUkey, Compilation, - CompilationAdditionalModuleRuntimeRequirements, CompilationParams, CompilerCompilation, Filename, - Module, ModuleIdentifier, PathData, Plugin, RuntimeGlobals, + ChunkInitFragments, ChunkUkey, Compilation, CompilationAdditionalModuleRuntimeRequirements, + CompilationParams, CompilerCompilation, Filename, Module, ModuleIdentifier, PathData, Plugin, + RuntimeCodeTemplate, RuntimeGlobals, rspack_sources::{BoxSource, RawStringSource, Source, SourceExt}, }; use rspack_error::Result; @@ -86,7 +86,7 @@ async fn render_module_content( module: &dyn Module, render_source: &mut RenderSource, _init_fragments: &mut ChunkInitFragments, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let origin_source = render_source.source.clone(); if let Some(cached_source) = self.cache.get(&origin_source) { diff --git a/crates/rspack_plugin_devtool/src/eval_source_map_dev_tool_plugin.rs b/crates/rspack_plugin_devtool/src/eval_source_map_dev_tool_plugin.rs index b4d7ffdce1ad..a21d09adea2e 100644 --- a/crates/rspack_plugin_devtool/src/eval_source_map_dev_tool_plugin.rs +++ b/crates/rspack_plugin_devtool/src/eval_source_map_dev_tool_plugin.rs @@ -3,9 +3,9 @@ use std::{borrow::Cow, sync::Arc}; use derive_more::Debug; use futures::future::join_all; use rspack_core::{ - ChunkCodeTemplate, ChunkGraph, ChunkInitFragments, ChunkUkey, Compilation, + ChunkGraph, ChunkInitFragments, ChunkUkey, Compilation, CompilationAdditionalModuleRuntimeRequirements, CompilationParams, CompilerCompilation, Filename, - Module, ModuleIdentifier, PathData, Plugin, RuntimeGlobals, + Module, ModuleIdentifier, PathData, Plugin, RuntimeCodeTemplate, RuntimeGlobals, rspack_sources::{BoxSource, MapOptions, ObjectPool, RawStringSource, Source, SourceExt}, }; use rspack_error::Result; @@ -96,7 +96,7 @@ async fn render_module_content( module: &dyn Module, render_source: &mut RenderSource, _init_fragments: &mut ChunkInitFragments, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let output_options = &compilation.options.output; let chunk = compilation diff --git a/crates/rspack_plugin_esm_library/src/chunk_link.rs b/crates/rspack_plugin_esm_library/src/chunk_link.rs index b529dd4eabca..4b8d43c41275 100644 --- a/crates/rspack_plugin_esm_library/src/chunk_link.rs +++ b/crates/rspack_plugin_esm_library/src/chunk_link.rs @@ -2,8 +2,8 @@ use std::{borrow::Cow, sync::Arc}; use rspack_collections::{IdentifierIndexMap, IdentifierIndexSet, IdentifierMap, IdentifierSet}; use rspack_core::{ - BoxChunkInitFragment, ChunkCodeTemplate, ChunkGraph, ChunkUkey, Compilation, ImportSpec, - ModuleGraph, ModuleIdentifier, RuntimeGlobals, find_new_name, + BoxChunkInitFragment, ChunkGraph, ChunkUkey, Compilation, ImportSpec, ModuleGraph, + ModuleIdentifier, RuntimeCodeTemplate, RuntimeGlobals, find_new_name, rspack_sources::{ConcatSource, RawStringSource}, }; use rspack_util::fx_hash::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; @@ -163,7 +163,7 @@ impl ExternalInterop { pub fn render( &self, compilation: &Compilation, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> ConcatSource { let mut source = ConcatSource::default(); let name = self.required_symbol.as_ref(); diff --git a/crates/rspack_plugin_esm_library/src/plugin.rs b/crates/rspack_plugin_esm_library/src/plugin.rs index d6010981712c..793d69be0008 100644 --- a/crates/rspack_plugin_esm_library/src/plugin.rs +++ b/crates/rspack_plugin_esm_library/src/plugin.rs @@ -9,8 +9,8 @@ use rspack_collections::{ Identifiable, Identifier, IdentifierIndexMap, IdentifierMap, IdentifierSet, }; use rspack_core::{ - ApplyContext, AssetInfo, AsyncModulesArtifact, BoxModule, BuildModuleGraphArtifact, - ChunkCodeTemplate, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, + ApplyContext, AssetInfo, AsyncModulesArtifact, BoxModule, BuildModuleGraphArtifact, ChunkUkey, + Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationAdditionalModuleRuntimeRequirements, CompilationAdditionalTreeRuntimeRequirements, CompilationAfterCodeGeneration, CompilationConcatenationScope, CompilationFinishModules, CompilationOptimizeChunkModules, CompilationOptimizeChunks, CompilationOptimizeDependencies, @@ -19,8 +19,8 @@ use rspack_core::{ ExportsInfoArtifact, ExternalModuleInfo, GetTargetResult, Logger, ModuleFactoryCreateData, ModuleGraph, ModuleIdentifier, ModuleInfo, ModuleType, NormalModuleFactoryAfterFactorize, NormalModuleFactoryParser, ParserAndGenerator, ParserOptions, Plugin, REQUIRE_SCOPE_GLOBALS, - RuntimeGlobals, RuntimeModule, SideEffectsOptimizeArtifact, SideEffectsStateArtifact, get_target, - is_esm_dep_like, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, SideEffectsOptimizeArtifact, + SideEffectsStateArtifact, get_target, is_esm_dep_like, rspack_sources::{ReplaceSource, Source}, }; use rspack_error::{Diagnostic, Result}; @@ -284,7 +284,7 @@ async fn render_chunk_content( compilation: &Compilation, chunk_ukey: &ChunkUkey, asset_info: &mut AssetInfo, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result> { self .render_chunk(compilation, chunk_ukey, asset_info, runtime_template) diff --git a/crates/rspack_plugin_esm_library/src/render.rs b/crates/rspack_plugin_esm_library/src/render.rs index f374de03026c..4655342956eb 100644 --- a/crates/rspack_plugin_esm_library/src/render.rs +++ b/crates/rspack_plugin_esm_library/src/render.rs @@ -2,8 +2,8 @@ use std::{borrow::Cow, sync::Arc}; use rspack_collections::IdentifierIndexSet; use rspack_core::{ - AssetInfo, Chunk, ChunkCodeTemplate, ChunkGraph, ChunkGroup, ChunkRenderContext, ChunkUkey, - Compilation, ConcatenatedModuleInfo, InitFragment, ModuleIdentifier, PathData, PathInfo, + AssetInfo, Chunk, ChunkGraph, ChunkGroup, ChunkRenderContext, ChunkUkey, Compilation, + ConcatenatedModuleInfo, InitFragment, ModuleIdentifier, PathData, PathInfo, RuntimeCodeTemplate, RuntimeGlobals, RuntimeVariable, SourceType, export_name, get_js_chunk_filename_template, get_undo_path, render_imports, render_init_fragments, rspack_sources::{ConcatSource, RawStringSource, ReplaceSource, Source, SourceExt}, @@ -135,7 +135,7 @@ impl EsmLibraryPlugin { compilation: &Compilation, chunk_ukey: &ChunkUkey, asset_info: &mut AssetInfo, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result> { let module_graph = compilation.get_module_graph(); @@ -155,11 +155,11 @@ impl EsmLibraryPlugin { let chunk = get_chunk(compilation, *chunk_ukey); let rspack_module_runtime_template; - let module_runtime_template = if runtime_template.uses_runtime_context() { + let module_runtime_template = if runtime_template.render_mode().is_legacy() { + runtime_template + } else { rspack_module_runtime_template = compilation.runtime_template.create_chunk_code_template(); &rspack_module_runtime_template - } else { - runtime_template }; let filename_template = get_js_chunk_filename_template( chunk, @@ -225,10 +225,10 @@ impl EsmLibraryPlugin { } if !decl_inner.source().is_empty() { - let register_modules = if runtime_template.uses_runtime_context() { - runtime_template.render_runtime_globals(&RuntimeGlobals::MODULE_FACTORIES) - } else { + let register_modules = if runtime_template.render_mode().is_legacy() { runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE) + } else { + runtime_template.render_runtime_globals(&RuntimeGlobals::MODULE_FACTORIES) }; decl_source.add(RawStringSource::from(format!( "{register_modules}.add({{\n" @@ -324,10 +324,10 @@ var {} = {{}}; && effective_tree_requirements .intersects(RuntimeGlobals::REQUIRE | RuntimeGlobals::REQUIRE_SCOPE) { - export_specifiers.insert(Cow::Owned(if runtime_template.uses_runtime_context() { - runtime_template.render_runtime_variable(&RuntimeVariable::Context) - } else { + export_specifiers.insert(Cow::Owned(if runtime_template.render_mode().is_legacy() { runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE) + } else { + runtime_template.render_runtime_variable(&RuntimeVariable::Context) })); } } @@ -470,10 +470,10 @@ var {} = {{}}; } let require_ident = module_runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE); - let runtime_import_ident = if module_runtime_template.uses_runtime_context() { - module_runtime_template.render_runtime_variable(&RuntimeVariable::Context) - } else { + let runtime_import_ident = if module_runtime_template.render_mode().is_legacy() { require_ident.clone() + } else { + module_runtime_template.render_runtime_variable(&RuntimeVariable::Context) }; let import_spec_imports_require = |import_spec: &rspack_core::ImportSpec| { let is_runtime_import = @@ -820,7 +820,7 @@ var {} = {{}}; chunk_ukey: &ChunkUkey, compilation: &Compilation, runtime_requirements: RuntimeGlobals, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { let module_factories: bool = runtime_requirements.contains(RuntimeGlobals::MODULE_FACTORIES); let require_function = runtime_requirements.contains(RuntimeGlobals::REQUIRE); @@ -865,13 +865,13 @@ var {} = {{}}; ))); } - if runtime_template.uses_runtime_context() + let should_render_runtime_context = !runtime_template.render_mode().is_legacy() && (module_factories || runtime_requirements.contains(RuntimeGlobals::MODULE_CACHE) || intercept_module_execution || use_require - || require_scope_used) - { + || require_scope_used); + if should_render_runtime_context { let runtime_context = runtime_template.render_runtime_variable(&RuntimeVariable::Context); source.add(RawStringSource::from(format!( "var {runtime_context} = {{}};\n" @@ -976,7 +976,7 @@ var {} = {{}}; compilation: &Compilation, chunk_link: &ChunkLinkContext, already_required: &mut IdentifierIndexSet, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> ConcatSource { let mut source = ConcatSource::default(); let module_graph = compilation.get_module_graph(); diff --git a/crates/rspack_plugin_esm_library/src/runtime.rs b/crates/rspack_plugin_esm_library/src/runtime.rs index 8d9c6bd5622f..aa8d428492fe 100644 --- a/crates/rspack_plugin_esm_library/src/runtime.rs +++ b/crates/rspack_plugin_esm_library/src/runtime.rs @@ -34,12 +34,12 @@ impl RuntimeModule for EsmRegisterModuleRuntimeModule { let module_factories = context .runtime_template .render_runtime_globals(&RuntimeGlobals::MODULE_FACTORIES); - let register_modules = if context.runtime_template.uses_runtime_context() { - module_factories.clone() - } else { + let register_modules = if context.runtime_template.render_mode().is_legacy() { context .runtime_template .render_runtime_globals(&RuntimeGlobals::REQUIRE) + } else { + module_factories.clone() }; Ok(format!( "{register_modules}.add = function registerModules(modules) {{ Object.assign({module_factories}, modules) }}\n" diff --git a/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs index 0f6731984a85..85a8fefba09a 100644 --- a/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs @@ -1,7 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkInitFragments, ChunkUkey, Compilation, CompilationParams, - CompilerCompilation, InitFragmentExt, InitFragmentKey, InitFragmentStage, Module, - NormalInitFragment, Plugin, + ChunkInitFragments, ChunkUkey, Compilation, CompilationParams, CompilerCompilation, + InitFragmentExt, InitFragmentKey, InitFragmentStage, Module, NormalInitFragment, Plugin, + RuntimeCodeTemplate, }; use rspack_error::Result; use rspack_hook::{plugin, plugin_hook}; @@ -35,7 +35,7 @@ async fn render_module_content( module: &dyn Module, _source: &mut RenderSource, init_fragments: &mut ChunkInitFragments, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { if module.build_info().need_create_require { let need_prefix = compilation diff --git a/crates/rspack_plugin_javascript/src/plugin/drive.rs b/crates/rspack_plugin_javascript/src/plugin/drive.rs index 2b23aea84091..184469dfccbf 100644 --- a/crates/rspack_plugin_javascript/src/plugin/drive.rs +++ b/crates/rspack_plugin_javascript/src/plugin/drive.rs @@ -1,19 +1,19 @@ use rspack_core::{ - AssetInfo, BoxModule, Chunk, ChunkCodeTemplate, ChunkInitFragments, ChunkUkey, Compilation, - Module, ModuleIdentifier, rspack_sources::BoxSource, + AssetInfo, BoxModule, Chunk, ChunkInitFragments, ChunkUkey, Compilation, Module, + ModuleIdentifier, RuntimeCodeTemplate, rspack_sources::BoxSource, }; use rspack_hash::RspackHasher; use rspack_hook::define_hook; #[cfg(allocative)] use rspack_util::allocative; -define_hook!(JavascriptModulesRenderChunk: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, source: &mut RenderSource, runtime_template: &ChunkCodeTemplate)); -define_hook!(JavascriptModulesRenderChunkContent: SeriesBail(compilation: &Compilation, chunk_ukey: &ChunkUkey, asset_info: &mut AssetInfo, runtime_template: &ChunkCodeTemplate) -> RenderSource); -define_hook!(JavascriptModulesRender: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, source: &mut RenderSource, runtime_template: &ChunkCodeTemplate)); -define_hook!(JavascriptModulesRenderStartup: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, module: &ModuleIdentifier, source: &mut RenderSource, runtime_template: &ChunkCodeTemplate)); -define_hook!(JavascriptModulesRenderModuleContent: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey,module: &dyn Module, source: &mut RenderSource, init_fragments: &mut ChunkInitFragments, runtime_template: &ChunkCodeTemplate),tracing=false); -define_hook!(JavascriptModulesRenderModuleContainer: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey,module: &dyn Module, source: &mut RenderSource, init_fragments: &mut ChunkInitFragments, runtime_template: &ChunkCodeTemplate),tracing=false); -define_hook!(JavascriptModulesRenderModulePackage: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, module: &dyn Module, source: &mut RenderSource, init_fragments: &mut ChunkInitFragments, runtime_template: &ChunkCodeTemplate),tracing=false); +define_hook!(JavascriptModulesRenderChunk: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, source: &mut RenderSource, runtime_template: &RuntimeCodeTemplate)); +define_hook!(JavascriptModulesRenderChunkContent: SeriesBail(compilation: &Compilation, chunk_ukey: &ChunkUkey, asset_info: &mut AssetInfo, runtime_template: &RuntimeCodeTemplate) -> RenderSource); +define_hook!(JavascriptModulesRender: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, source: &mut RenderSource, runtime_template: &RuntimeCodeTemplate)); +define_hook!(JavascriptModulesRenderStartup: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, module: &ModuleIdentifier, source: &mut RenderSource, runtime_template: &RuntimeCodeTemplate)); +define_hook!(JavascriptModulesRenderModuleContent: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey,module: &dyn Module, source: &mut RenderSource, init_fragments: &mut ChunkInitFragments, runtime_template: &RuntimeCodeTemplate),tracing=false); +define_hook!(JavascriptModulesRenderModuleContainer: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey,module: &dyn Module, source: &mut RenderSource, init_fragments: &mut ChunkInitFragments, runtime_template: &RuntimeCodeTemplate),tracing=false); +define_hook!(JavascriptModulesRenderModulePackage: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, module: &dyn Module, source: &mut RenderSource, init_fragments: &mut ChunkInitFragments, runtime_template: &RuntimeCodeTemplate),tracing=false); define_hook!(JavascriptModulesChunkHash: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey, hasher: &mut RspackHasher)); define_hook!(JavascriptModulesInlineInRuntimeBailout: SeriesBail(compilation: &Compilation) -> String); define_hook!(JavascriptModulesEmbedInRuntimeBailout: SeriesBail(compilation: &Compilation, module: &BoxModule, chunk: &Chunk) -> String); diff --git a/crates/rspack_plugin_javascript/src/plugin/mod.rs b/crates/rspack_plugin_javascript/src/plugin/mod.rs index 8121649db89a..0cfa50497813 100644 --- a/crates/rspack_plugin_javascript/src/plugin/mod.rs +++ b/crates/rspack_plugin_javascript/src/plugin/mod.rs @@ -28,9 +28,9 @@ pub use mangle_exports_plugin::*; pub use module_concatenation_plugin::*; use rspack_collections::{Identifier, IdentifierDashMap, IdentifierLinkedMap, IdentifierMap}; use rspack_core::{ - ChunkCodeTemplate, ChunkGraph, ChunkGroupUkey, ChunkInitFragments, ChunkRenderContext, ChunkUkey, + ChunkGraph, ChunkGroupUkey, ChunkInitFragments, ChunkRenderContext, ChunkUkey, CodeGenerationDataTopLevelDeclarations, Compilation, CompilationId, ConcatenatedModuleIdent, - ExportsArgument, Module, RuntimeGlobals, RuntimeVariable, SourceType, + ExportsArgument, Module, RuntimeCodeTemplate, RuntimeGlobals, RuntimeVariable, SourceType, concatenated_module::{collect_ident, find_new_name}, render_init_fragments, reserved_names::RESERVED_NAMES_ATOM_SET, @@ -134,24 +134,19 @@ impl JsPlugin { pub fn render_require<'me>( chunk_ukey: &ChunkUkey, compilation: &'me Compilation, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Vec> { - if compilation - .options - .experiments - .runtime_mode - .uses_runtime_context() - { - return Self::render_rspack_require(chunk_ukey, compilation, runtime_template); + if runtime_template.render_mode().is_legacy() { + Self::render_webpack_require(chunk_ukey, compilation, runtime_template) + } else { + Self::render_rspack_require(chunk_ukey, compilation, runtime_template) } - - Self::render_webpack_require(chunk_ukey, compilation, runtime_template) } pub fn render_webpack_require<'me>( chunk_ukey: &ChunkUkey, compilation: &'me Compilation, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Vec> { let runtime_requirements = compilation .cgc_runtime_requirements_artifact @@ -258,24 +253,19 @@ var module = ({module_cache}[moduleId] = {{"#, pub async fn render_bootstrap<'me>( chunk_ukey: &ChunkUkey, compilation: &'me Compilation, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result> { - if compilation - .options - .experiments - .runtime_mode - .uses_runtime_context() - { - return Self::render_rspack_bootstrap(chunk_ukey, compilation, runtime_template).await; + if runtime_template.render_mode().is_legacy() { + Self::render_webpack_bootstrap(chunk_ukey, compilation, runtime_template).await + } else { + Self::render_rspack_bootstrap(chunk_ukey, compilation, runtime_template).await } - - Self::render_webpack_bootstrap(chunk_ukey, compilation, runtime_template).await } pub async fn render_webpack_bootstrap<'me>( chunk_ukey: &ChunkUkey, compilation: &'me Compilation, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result> { let runtime_requirements = compilation .cgc_runtime_requirements_artifact @@ -711,22 +701,17 @@ var {} = {{}}; compilation: &Compilation, chunk_ukey: &ChunkUkey, output_path: &str, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { - if compilation - .options - .experiments - .runtime_mode - .uses_runtime_context() - { - return self + if runtime_template.render_mode().is_legacy() { + self + .render_webpack_main(compilation, chunk_ukey, output_path, runtime_template) + .await + } else { + self .render_rspack_main(compilation, chunk_ukey, output_path, runtime_template) - .await; + .await } - - self - .render_webpack_main(compilation, chunk_ukey, output_path, runtime_template) - .await } pub async fn render_webpack_main( @@ -734,7 +719,7 @@ var {} = {{}}; compilation: &Compilation, chunk_ukey: &ChunkUkey, output_path: &str, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { let js_plugin_hooks = Self::get_compilation_hooks(compilation.id()); let hooks = js_plugin_hooks @@ -1072,7 +1057,7 @@ var {} = {{}}; has_chunk_modules_result: bool, output_path: &str, hooks: &JavascriptModulesPluginHooks, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result>>> { let inner_strict = !all_strict && all_modules.iter().all(|m| m.build_info().strict); let is_multiple_entries = inlined_modules.len() > 1; @@ -1412,7 +1397,7 @@ var {} = {{}}; compilation: &Compilation, chunk_ukey: &ChunkUkey, output_path: &str, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { let js_plugin_hooks = Self::get_compilation_hooks(compilation.id()); let hooks = js_plugin_hooks diff --git a/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs b/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs index c79805d1cb19..939675dc806a 100644 --- a/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs +++ b/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs @@ -1,9 +1,10 @@ use std::borrow::Cow; use rspack_core::{ - ChunkCodeTemplate, ChunkGraph, ChunkInitFragments, ChunkRenderContext, ChunkUkey, - CodeGenerationDataTopLevelDeclarations, Compilation, ExportsArgument, Module, RuntimeGlobals, - RuntimeVariable, SourceType, property_access, render_init_fragments, + ChunkGraph, ChunkInitFragments, ChunkRenderContext, ChunkUkey, + CodeGenerationDataTopLevelDeclarations, Compilation, ExportsArgument, Module, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeVariable, SourceType, property_access, + render_init_fragments, rspack_sources::{BoxSource, ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::Result; @@ -21,7 +22,7 @@ impl JsPlugin { pub fn render_rspack_require<'me>( chunk_ukey: &ChunkUkey, compilation: &'me Compilation, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Vec> { let runtime_requirements = compilation .cgc_runtime_requirements_artifact @@ -127,7 +128,7 @@ var module = ({module_cache}[moduleId] = {{"#, pub async fn render_rspack_bootstrap<'me>( chunk_ukey: &ChunkUkey, compilation: &'me Compilation, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result> { let runtime_requirements = compilation .cgc_runtime_requirements_artifact @@ -579,7 +580,7 @@ impl JsPlugin { compilation: &Compilation, chunk_ukey: &ChunkUkey, output_path: &str, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { let js_plugin_hooks = Self::get_compilation_hooks(compilation.id()); let hooks = js_plugin_hooks @@ -693,13 +694,15 @@ impl JsPlugin { header.push('\n'); sources.add(RawStringSource::from(header)); } + let should_render_runtime_context = + !runtime_template.render_mode().is_legacy() && !has_bootstrap_runtime_context; if compilation .build_chunk_graph_artifact .chunk_graph .has_chunk_runtime_modules(chunk_ukey) { sources.add(render_runtime_modules(compilation, chunk_ukey, runtime_template).await?); - } else if runtime_template.uses_runtime_context() && !has_bootstrap_runtime_context { + } else if should_render_runtime_context { sources.add(RawStringSource::from(render_runtime_context_declaration( runtime_template, ))); diff --git a/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs index 34e8c4bcc539..f45e42ff4760 100644 --- a/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs @@ -1,9 +1,10 @@ use concat_string::concat_string; use rspack_core::{ - ChunkCodeTemplate, ChunkInitFragments, ChunkUkey, CodeGenerationDataFilename, Compilation, - CompilationParams, CompilerCompilation, DependencyId, JavascriptParserUrl, Module, ModuleType, + ChunkInitFragments, ChunkUkey, CodeGenerationDataFilename, Compilation, CompilationParams, + CompilerCompilation, DependencyId, JavascriptParserUrl, Module, ModuleType, NormalModuleFactoryParser, ParserAndGenerator, ParserOptions, PathData, Plugin, PublicPath, - RuntimeSpec, SourceType, URLStaticMode, get_js_chunk_filename_template, get_undo_path, + RuntimeCodeTemplate, RuntimeSpec, SourceType, URLStaticMode, get_js_chunk_filename_template, + get_undo_path, rspack_sources::{BoxSource, ReplaceSource, SourceExt}, }; use rspack_error::Result; @@ -196,7 +197,7 @@ async fn render_module_content( module: &dyn Module, render_source: &mut RenderSource, _init_fragments: &mut ChunkInitFragments, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let runtime = compilation .build_chunk_graph_artifact diff --git a/crates/rspack_plugin_javascript/src/runtime.rs b/crates/rspack_plugin_javascript/src/runtime.rs index ef1fab0c39b2..fdb9a4f29de8 100644 --- a/crates/rspack_plugin_javascript/src/runtime.rs +++ b/crates/rspack_plugin_javascript/src/runtime.rs @@ -1,8 +1,8 @@ use rayon::prelude::*; use rspack_core::{ - ChunkCodeTemplate, ChunkGraph, ChunkInitFragments, ChunkKind, ChunkUkey, - CodeGenerationPublicPathAutoReplace, Compilation, Module, RuntimeGlobals, - RuntimeModuleGenerateContext, SourceType, + ChunkGraph, ChunkInitFragments, ChunkKind, ChunkUkey, CodeGenerationPublicPathAutoReplace, + Compilation, Module, RuntimeCodeTemplate, RuntimeGlobals, RuntimeModuleGenerateContext, + SourceType, chunk_graph_chunk::ChunkIdSet, get_undo_path, render_runtime_module_source, rspack_sources::{ @@ -29,7 +29,7 @@ pub async fn render_chunk_modules( all_strict: bool, output_path: &str, hooks: &JavascriptModulesPluginHooks, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result> { let module_sources = rspack_parallel::scope::<_, _>(|token| { ordered_modules.iter().for_each(|module| { @@ -118,7 +118,7 @@ pub async fn render_module( factory: bool, output_path: &str, hooks: &JavascriptModulesPluginHooks, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result> { let chunk = compilation .build_chunk_graph_artifact @@ -332,7 +332,7 @@ pub async fn render_module( pub async fn render_chunk_runtime_modules( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { let runtime_modules_sources = if compilation.options.experiments.runtime_mode == RuntimeMode::Rspack { @@ -382,12 +382,12 @@ pub async fn render_chunk_runtime_modules( pub async fn render_runtime_modules( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { if compilation.options.experiments.runtime_mode == RuntimeMode::Rspack { render_rspack_runtime_modules(compilation, chunk_ukey, runtime_template).await } else { - render_webpack_runtime_modules(compilation, chunk_ukey, runtime_template).await + render_webpack_runtime_modules(compilation, chunk_ukey).await } } @@ -396,7 +396,6 @@ pub(crate) type RuntimeModuleSourceItem = (BoxSource, RuntimeGlobals, RuntimeGlo pub(crate) async fn render_runtime_module_sources( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, reject_custom_runtime_modules: bool, ) -> Result> { let runtime_mode = compilation.options.experiments.runtime_mode; @@ -415,9 +414,9 @@ pub(crate) async fn render_runtime_module_sources( ) }) .for_each(|(source, module)| { - let s = unsafe { token.used((compilation, source, module, runtime_template)) }; + let s = unsafe { token.used((compilation, source, module)) }; s.spawn( - move |(compilation, source, module, runtime_template)| async move { + move |(compilation, source, module)| async move { if source.size() == 0 { return Ok(( ConcatSource::default().boxed(), @@ -443,11 +442,7 @@ pub(crate) async fn render_runtime_module_sources( .output .environment .supports_arrow_function(); - let source = if !(module.full_hash() - || module.dependent_hash() - || (runtime_template.uses_runtime_context() - && !runtime_template.uses_lexical_runtime_globals())) - { + let source = if !(module.full_hash() || module.dependent_hash()) { if let Some(custom_source) = module.get_custom_source() { RawStringSource::from(custom_source).boxed() } else { @@ -457,7 +452,7 @@ pub(crate) async fn render_runtime_module_sources( if let Some(custom_source) = module.get_custom_source() { RawStringSource::from(custom_source).boxed() } else { - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation.runtime_template.create_runtime_module_code_template(); let context = RuntimeModuleGenerateContext { compilation, runtime_template: &runtime_template, @@ -501,10 +496,9 @@ pub(crate) async fn render_runtime_module_sources( async fn render_webpack_runtime_modules( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, ) -> Result { let runtime_module_sources = - render_runtime_module_sources(compilation, chunk_ukey, runtime_template, false).await?; + render_runtime_module_sources(compilation, chunk_ukey, false).await?; let mut sources = ConcatSource::default(); for (runtime_module_source, _, _, _) in runtime_module_sources { diff --git a/crates/rspack_plugin_javascript/src/runtime_context.rs b/crates/rspack_plugin_javascript/src/runtime_context.rs index f4d5bcc229e3..b7dc1620142c 100644 --- a/crates/rspack_plugin_javascript/src/runtime_context.rs +++ b/crates/rspack_plugin_javascript/src/runtime_context.rs @@ -1,7 +1,7 @@ use std::sync::LazyLock; use rspack_core::{ - ChunkCodeTemplate, ChunkKind, ChunkUkey, Compilation, RuntimeGlobals, RuntimeProxyMetadata, + ChunkKind, ChunkUkey, Compilation, RuntimeCodeTemplate, RuntimeGlobals, RuntimeProxyMetadata, RuntimeVariable, SourceType, property_access, render_lexical_declarations, rspack_sources::{BoxSource, ConcatSource, RawStringSource, SourceExt}, runtime_module_owned_define_fields, @@ -59,12 +59,12 @@ fn filter_unused_module_runtime_bindings( fields } -pub fn render_runtime_context_declaration(runtime_template: &ChunkCodeTemplate) -> String { +pub fn render_runtime_context_declaration(runtime_template: &RuntimeCodeTemplate) -> String { let runtime_context = runtime_template.render_runtime_variable(&RuntimeVariable::Context); format!("var {runtime_context}={{}};\n") } -pub fn render_runtime_context_require_assignment(runtime_template: &ChunkCodeTemplate) -> String { +pub fn render_runtime_context_require_assignment(runtime_template: &RuntimeCodeTemplate) -> String { format!( "{} = {};\n", runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE), @@ -75,10 +75,9 @@ pub fn render_runtime_context_require_assignment(runtime_template: &ChunkCodeTem pub async fn render_runtime_chunk_runtime_modules( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { - let runtime_module_sources = - render_runtime_module_sources(compilation, chunk_ukey, runtime_template, true).await?; + let runtime_module_sources = render_runtime_module_sources(compilation, chunk_ukey, true).await?; let mut sources = ConcatSource::default(); if runtime_module_sources.is_empty() { return Ok(sources.boxed()); @@ -222,10 +221,9 @@ pub async fn render_runtime_chunk_runtime_modules( pub async fn render_chunk_runtime_modules( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { - let runtime_module_sources = - render_runtime_module_sources(compilation, chunk_ukey, runtime_template, true).await?; + let runtime_module_sources = render_runtime_module_sources(compilation, chunk_ukey, true).await?; let mut sources = ConcatSource::default(); if runtime_module_sources.is_empty() { return Ok(sources.boxed()); @@ -308,10 +306,9 @@ pub async fn render_chunk_runtime_modules( pub async fn render_hot_update_chunk_runtime_modules( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { - let runtime_module_sources = - render_runtime_module_sources(compilation, chunk_ukey, runtime_template, true).await?; + let runtime_module_sources = render_runtime_module_sources(compilation, chunk_ukey, true).await?; let mut sources = ConcatSource::default(); if runtime_module_sources.is_empty() { return Ok(sources.boxed()); @@ -413,7 +410,7 @@ Object.defineProperty({runtime_context}, {json_key}, {{ configurable: true, get: pub async fn render_rspack_runtime_modules( compilation: &Compilation, chunk_ukey: &ChunkUkey, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result { let chunk = compilation .build_chunk_graph_artifact diff --git a/crates/rspack_plugin_library/src/amd_library_plugin.rs b/crates/rspack_plugin_library/src/amd_library_plugin.rs index 3323713e4cee..b9347c1051fe 100644 --- a/crates/rspack_plugin_library/src/amd_library_plugin.rs +++ b/crates/rspack_plugin_library/src/amd_library_plugin.rs @@ -1,8 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, - CompilationParams, CompilerCompilation, ExternalModule, Filename, LibraryName, - LibraryNonUmdObject, LibraryOptions, LibraryType, PathData, Plugin, RuntimeGlobals, - RuntimeModule, SourceType, + ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationParams, + CompilerCompilation, ExternalModule, Filename, LibraryName, LibraryNonUmdObject, LibraryOptions, + LibraryType, PathData, Plugin, RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, SourceType, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::{Result, error_bail}; @@ -91,7 +90,7 @@ async fn render( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(options) = self.get_options_for_chunk(compilation, chunk_ukey)? else { return Ok(()); diff --git a/crates/rspack_plugin_library/src/assign_library_plugin.rs b/crates/rspack_plugin_library/src/assign_library_plugin.rs index e25eb6512d1c..fb16dcf1325a 100644 --- a/crates/rspack_plugin_library/src/assign_library_plugin.rs +++ b/crates/rspack_plugin_library/src/assign_library_plugin.rs @@ -3,13 +3,13 @@ use std::sync::LazyLock; use futures::future::join_all; use regex::Regex; use rspack_core::{ - AsyncModulesArtifact, BoxModule, CanInlineUse, Chunk, ChunkCodeTemplate, ChunkUkey, + AsyncModulesArtifact, BoxModule, CanInlineUse, Chunk, ChunkUkey, CodeGenerationDataTopLevelDeclarations, Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationFinishModules, CompilationParams, CompilerCompilation, EntryData, ExportProvided, ExportsInfoArtifact, Filename, LibraryExport, LibraryName, LibraryNonUmdObject, LibraryOptions, ModuleIdentifier, PathData, Plugin, - RuntimeGlobals, RuntimeModule, RuntimeVariable, SideEffectsStateArtifact, SourceType, UsageState, - get_entry_runtime, property_access, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, RuntimeVariable, SideEffectsStateArtifact, + SourceType, UsageState, get_entry_runtime, property_access, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, to_identifier, }; @@ -214,7 +214,7 @@ async fn render( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(options) = self.get_options_for_chunk(compilation, chunk_ukey)? else { return Ok(()); @@ -249,7 +249,7 @@ async fn render_startup( chunk_ukey: &ChunkUkey, module: &ModuleIdentifier, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(options) = self.get_options_for_chunk(compilation, chunk_ukey)? else { return Ok(()); diff --git a/crates/rspack_plugin_library/src/export_property_library_plugin.rs b/crates/rspack_plugin_library/src/export_property_library_plugin.rs index 34f8b50f8e73..e4391470640a 100644 --- a/crates/rspack_plugin_library/src/export_property_library_plugin.rs +++ b/crates/rspack_plugin_library/src/export_property_library_plugin.rs @@ -1,8 +1,8 @@ use rspack_core::{ - AsyncModulesArtifact, CanInlineUse, ChunkCodeTemplate, ChunkUkey, Compilation, + AsyncModulesArtifact, CanInlineUse, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationFinishModules, CompilationParams, CompilerCompilation, EntryData, ExportsInfoArtifact, LibraryExport, LibraryOptions, LibraryType, - ModuleIdentifier, Plugin, RuntimeGlobals, RuntimeModule, RuntimeVariable, + ModuleIdentifier, Plugin, RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, RuntimeVariable, SideEffectsStateArtifact, UsageState, get_entry_runtime, property_access, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; @@ -75,7 +75,7 @@ async fn render_startup( chunk_ukey: &ChunkUkey, _module: &ModuleIdentifier, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(options) = self.get_options_for_chunk(compilation, chunk_ukey) else { return Ok(()); diff --git a/crates/rspack_plugin_library/src/jsonp_library_plugin.rs b/crates/rspack_plugin_library/src/jsonp_library_plugin.rs index 770decfe620a..4d3e9274f216 100644 --- a/crates/rspack_plugin_library/src/jsonp_library_plugin.rs +++ b/crates/rspack_plugin_library/src/jsonp_library_plugin.rs @@ -1,7 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, - CompilationParams, CompilerCompilation, Filename, LibraryName, LibraryNonUmdObject, - LibraryOptions, LibraryType, PathData, Plugin, RuntimeGlobals, RuntimeModule, SourceType, + ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationParams, + CompilerCompilation, Filename, LibraryName, LibraryNonUmdObject, LibraryOptions, LibraryType, + PathData, Plugin, RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, SourceType, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::{Result, error_bail}; @@ -73,7 +73,7 @@ async fn render( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(options) = self.get_options_for_chunk(compilation, chunk_ukey)? else { return Ok(()); diff --git a/crates/rspack_plugin_library/src/module_library_plugin.rs b/crates/rspack_plugin_library/src/module_library_plugin.rs index 40ae52020b32..dbb54a40f4bc 100644 --- a/crates/rspack_plugin_library/src/module_library_plugin.rs +++ b/crates/rspack_plugin_library/src/module_library_plugin.rs @@ -1,7 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkUkey, Compilation, CompilationParams, CompilerCompilation, - ExportProvided, ExportsType, LibraryOptions, ModuleGraph, ModuleIdentifier, Plugin, - RuntimeVariable, UsedNameItem, property_access, + ChunkUkey, Compilation, CompilationParams, CompilerCompilation, ExportProvided, ExportsType, + LibraryOptions, ModuleGraph, ModuleIdentifier, Plugin, RuntimeCodeTemplate, RuntimeVariable, + UsedNameItem, property_access, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, to_identifier, to_module_export_name, }; @@ -60,7 +60,7 @@ async fn render_startup( chunk_ukey: &ChunkUkey, module: &ModuleIdentifier, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(_) = self.get_options_for_chunk(compilation, chunk_ukey)? else { return Ok(()); diff --git a/crates/rspack_plugin_library/src/system_library_plugin.rs b/crates/rspack_plugin_library/src/system_library_plugin.rs index 9489a8ef1ea9..a5e2e33f91f1 100644 --- a/crates/rspack_plugin_library/src/system_library_plugin.rs +++ b/crates/rspack_plugin_library/src/system_library_plugin.rs @@ -1,7 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, - CompilationParams, CompilerCompilation, ExternalModule, ExternalRequest, Filename, LibraryName, - LibraryNonUmdObject, LibraryOptions, PathData, Plugin, RuntimeGlobals, RuntimeModule, + ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationParams, + CompilerCompilation, ExternalModule, ExternalRequest, Filename, LibraryName, LibraryNonUmdObject, + LibraryOptions, PathData, Plugin, RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::{Result, ToStringResultToRspackResultExt, error_bail}; @@ -82,7 +82,7 @@ async fn render( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(options) = self.get_options_for_chunk(compilation, chunk_ukey)? else { return Ok(()); diff --git a/crates/rspack_plugin_library/src/umd_library_plugin.rs b/crates/rspack_plugin_library/src/umd_library_plugin.rs index 1a5473c5dc05..761068e841b4 100644 --- a/crates/rspack_plugin_library/src/umd_library_plugin.rs +++ b/crates/rspack_plugin_library/src/umd_library_plugin.rs @@ -1,11 +1,11 @@ use std::borrow::Cow; use rspack_core::{ - Chunk, ChunkCodeTemplate, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, - CompilationParams, CompilerCompilation, ExportsInfoArtifact, ExternalModule, ExternalRequest, - Filename, LibraryAuxiliaryComment, LibraryCustomUmdObject, LibraryName, LibraryNonUmdObject, + Chunk, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationParams, + CompilerCompilation, ExportsInfoArtifact, ExternalModule, ExternalRequest, Filename, + LibraryAuxiliaryComment, LibraryCustomUmdObject, LibraryName, LibraryNonUmdObject, LibraryOptions, LibraryType, ModuleGraph, ModuleGraphCacheArtifact, PathData, Plugin, - RuntimeGlobals, RuntimeModule, SideEffectsStateArtifact, SourceType, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, SideEffectsStateArtifact, SourceType, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::{Result, error}; @@ -98,7 +98,7 @@ async fn render( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let Some(options) = self.get_options_for_chunk(compilation, chunk_ukey) else { return Ok(()); diff --git a/crates/rspack_plugin_mf/src/container/embed_federation_runtime_plugin.rs b/crates/rspack_plugin_mf/src/container/embed_federation_runtime_plugin.rs index 8c3760c01660..bcd14563c489 100644 --- a/crates/rspack_plugin_mf/src/container/embed_federation_runtime_plugin.rs +++ b/crates/rspack_plugin_mf/src/container/embed_federation_runtime_plugin.rs @@ -7,9 +7,9 @@ use std::sync::{Arc, Mutex}; use rspack_core::{ - ChunkCodeTemplate, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, - CompilationParams, CompilationRuntimeRequirementInTree, CompilerCompilation, DependencyId, - ModuleIdentifier, Plugin, RuntimeGlobals, RuntimeModule, + ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, CompilationParams, + CompilationRuntimeRequirementInTree, CompilerCompilation, DependencyId, ModuleIdentifier, Plugin, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::Result; @@ -183,7 +183,7 @@ async fn render_startup( chunk_ukey: &ChunkUkey, _module: &ModuleIdentifier, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let chunk = compilation .build_chunk_graph_artifact diff --git a/crates/rspack_plugin_mf/src/container/federation_data_runtime_module.rs b/crates/rspack_plugin_mf/src/container/federation_data_runtime_module.rs index a852ebf8917b..a7bbd7904eeb 100644 --- a/crates/rspack_plugin_mf/src/container/federation_data_runtime_module.rs +++ b/crates/rspack_plugin_mf/src/container/federation_data_runtime_module.rs @@ -52,7 +52,7 @@ impl RuntimeModule for FederationDataRuntimeModule { pub async fn federation_runtime_template( chunk: &Chunk, - runtime_template: &RuntimeCodeTemplate<'_>, + runtime_template: &RuntimeCodeTemplate, compilation: &Compilation, ) -> String { let federation_global = format!( diff --git a/crates/rspack_plugin_mf/src/lib.rs b/crates/rspack_plugin_mf/src/lib.rs index a8b8325457d3..408ace2c4b97 100644 --- a/crates/rspack_plugin_mf/src/lib.rs +++ b/crates/rspack_plugin_mf/src/lib.rs @@ -90,11 +90,11 @@ mod utils { simd_json::to_string(v).unwrap_or_else(|e| panic!("{e}: {v:?} should able to json stringify")) } - pub fn runtime_require_scope_name(runtime_template: &RuntimeCodeTemplate<'_>) -> String { - if runtime_template.uses_runtime_context() { - runtime_template.render_runtime_variable(&RuntimeVariable::Context) - } else { + pub fn runtime_require_scope_name(runtime_template: &RuntimeCodeTemplate) -> String { + if runtime_template.render_mode().is_legacy() { runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE) + } else { + runtime_template.render_runtime_variable(&RuntimeVariable::Context) } } diff --git a/crates/rspack_plugin_module_info_header/src/lib.rs b/crates/rspack_plugin_module_info_header/src/lib.rs index e5d3e9a9fc58..2df1c780fee0 100644 --- a/crates/rspack_plugin_module_info_header/src/lib.rs +++ b/crates/rspack_plugin_module_info_header/src/lib.rs @@ -2,10 +2,10 @@ use std::borrow::Cow; use rspack_cacheable::with::AsVecConverter; use rspack_core::{ - BuildMetaExportsType, ChunkCodeTemplate, ChunkGraph, ChunkInitFragments, ChunkUkey, Compilation, - CompilationParams, CompilerCompilation, ExportInfo, ExportProvided, ExportsInfoArtifact, - ExportsInfoData, GetTargetResult, Module, ModuleGraph, ModuleIdentifier, OptimizationBailoutItem, - Plugin, UsageState, get_target, + BuildMetaExportsType, ChunkGraph, ChunkInitFragments, ChunkUkey, Compilation, CompilationParams, + CompilerCompilation, ExportInfo, ExportProvided, ExportsInfoArtifact, ExportsInfoData, + GetTargetResult, Module, ModuleGraph, ModuleIdentifier, OptimizationBailoutItem, Plugin, + RuntimeCodeTemplate, UsageState, get_target, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, to_comment_with_nl, }; @@ -238,7 +238,7 @@ async fn render_js_module_package( module: &dyn Module, render_source: &mut RenderSource, _init_fragments: &mut ChunkInitFragments, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let mut new_source: ConcatSource = Default::default(); diff --git a/crates/rspack_plugin_rslib/src/plugin.rs b/crates/rspack_plugin_rslib/src/plugin.rs index 3db3e0c5b76f..e0cd71439804 100644 --- a/crates/rspack_plugin_rslib/src/plugin.rs +++ b/crates/rspack_plugin_rslib/src/plugin.rs @@ -6,10 +6,10 @@ use std::{ use cow_utils::CowUtils; use pathdiff::diff_paths; use rspack_core::{ - AssetEmittedInfo, AssetInfo, BuildModuleGraphArtifact, ChunkCodeTemplate, ChunkUkey, Compilation, - CompilationAsset, CompilationOptimizeDependencies, CompilationParams, CompilationProcessAssets, + AssetEmittedInfo, AssetInfo, BuildModuleGraphArtifact, ChunkUkey, Compilation, CompilationAsset, + CompilationOptimizeDependencies, CompilationParams, CompilationProcessAssets, CompilerAssetEmitted, CompilerCompilation, DependencyType, ExportsInfoArtifact, ModuleType, - NormalModuleFactoryParser, ParserAndGenerator, ParserOptions, Plugin, + NormalModuleFactoryParser, ParserAndGenerator, ParserOptions, Plugin, RuntimeCodeTemplate, SideEffectsOptimizeArtifact, get_module_directives, get_module_hashbang, rspack_sources::{ConcatSource, RawStringSource, Source, SourceExt}, }; @@ -249,7 +249,7 @@ async fn render( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - _runtime_template: &ChunkCodeTemplate, + _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { // NOTE: This function handles hashbang and directives for non new ESM library formats. // Similar logic exists in rspack_plugin_esm_library/src/render.rs for ESM format, diff --git a/crates/rspack_plugin_rstest/src/plugin.rs b/crates/rspack_plugin_rstest/src/plugin.rs index 9b4a6a42ecb3..4c0d2ef0b7c2 100644 --- a/crates/rspack_plugin_rstest/src/plugin.rs +++ b/crates/rspack_plugin_rstest/src/plugin.rs @@ -84,7 +84,9 @@ async fn runtime_module( return Ok(()); }; - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); match runtime_module.get_constructor_name().as_str() { "DefinePropertyGettersRuntimeModule" => { runtime_module.set_custom_source( @@ -283,7 +285,9 @@ impl RstestPlugin { } fn generate_define_property_getters_runtime_source(compilation: &Compilation) -> String { - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); let define_property_getters = runtime_template.render_runtime_globals(&RuntimeGlobals::DEFINE_PROPERTY_GETTERS); let has_own_property = diff --git a/crates/rspack_plugin_runtime/src/array_push_callback_chunk_format.rs b/crates/rspack_plugin_runtime/src/array_push_callback_chunk_format.rs index b4f1909f5fec..82f69c60176d 100644 --- a/crates/rspack_plugin_runtime/src/array_push_callback_chunk_format.rs +++ b/crates/rspack_plugin_runtime/src/array_push_callback_chunk_format.rs @@ -1,7 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkGraph, ChunkKind, ChunkUkey, Compilation, - CompilationAdditionalChunkRuntimeRequirements, CompilationParams, CompilerCompilation, Plugin, - RuntimeGlobals, RuntimeModule, RuntimeVariable, + ChunkGraph, ChunkKind, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, + CompilationParams, CompilerCompilation, Plugin, RuntimeCodeTemplate, RuntimeGlobals, + RuntimeModule, RuntimeVariable, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::Result; @@ -106,7 +106,7 @@ async fn render_chunk( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let hooks = JsPlugin::get_compilation_hooks(compilation.id()); let chunk = compilation diff --git a/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs b/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs index 879f4f126a7b..84d91acf1d64 100644 --- a/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs +++ b/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs @@ -1,7 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, - CompilationDependentFullHash, CompilationParams, CompilerCompilation, Plugin, RuntimeGlobals, - RuntimeModule, + ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, + CompilationDependentFullHash, CompilationParams, CompilerCompilation, Plugin, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, rspack_sources::{ConcatSource, RawStringSource, SourceExt}, }; use rspack_error::Result; @@ -123,7 +123,7 @@ async fn render_chunk( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let hooks = JsPlugin::get_compilation_hooks(compilation.id()); let chunk = compilation diff --git a/crates/rspack_plugin_runtime/src/helpers.rs b/crates/rspack_plugin_runtime/src/helpers.rs index 81c7b8a91375..483dace349b1 100644 --- a/crates/rspack_plugin_runtime/src/helpers.rs +++ b/crates/rspack_plugin_runtime/src/helpers.rs @@ -4,9 +4,9 @@ use itertools::Itertools; use regex::Regex; use rspack_collections::IdentifierLinkedMap; use rspack_core::{ - Chunk, ChunkCodeTemplate, ChunkGraph, ChunkGroupByUkey, ChunkGroupUkey, ChunkLoading, - ChunkLoadingType, ChunkUkey, Compilation, PathData, RuntimeGlobals, - RuntimeModuleRuntimeRequirements, RuntimeVariable, SourceType, + Chunk, ChunkGraph, ChunkGroupByUkey, ChunkGroupUkey, ChunkLoading, ChunkLoadingType, ChunkUkey, + Compilation, PathData, RuntimeCodeTemplate, RuntimeGlobals, RuntimeModuleRuntimeRequirements, + RuntimeVariable, SourceType, chunk_graph_chunk::ChunkIdSet, get_js_chunk_filename_template, rspack_sources::{BoxSource, RawStringSource, SourceExt}, @@ -225,7 +225,7 @@ pub fn generate_entry_startup( chunk: &ChunkUkey, entries: &IdentifierLinkedMap, passive: bool, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> BoxSource { let mut module_id_exprs = vec![]; let mut chunks_ids = ChunkIdSet::default(); diff --git a/crates/rspack_plugin_runtime/src/module_chunk_format.rs b/crates/rspack_plugin_runtime/src/module_chunk_format.rs index cddbf56cec76..6678038695f5 100644 --- a/crates/rspack_plugin_runtime/src/module_chunk_format.rs +++ b/crates/rspack_plugin_runtime/src/module_chunk_format.rs @@ -1,8 +1,7 @@ use rspack_core::{ - ChunkCodeTemplate, ChunkGraph, ChunkKind, ChunkUkey, Compilation, - CompilationAdditionalChunkRuntimeRequirements, CompilationDependentFullHash, CompilationParams, - CompilerCompilation, ModuleIdentifier, Plugin, RuntimeGlobals, RuntimeModule, RuntimeVariable, - SourceType, + ChunkGraph, ChunkKind, ChunkUkey, Compilation, CompilationAdditionalChunkRuntimeRequirements, + CompilationDependentFullHash, CompilationParams, CompilerCompilation, ModuleIdentifier, Plugin, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeModule, RuntimeVariable, SourceType, rspack_sources::{ConcatSource, RawStringSource, Source, SourceExt}, }; use rspack_error::Result; @@ -135,7 +134,7 @@ async fn render_chunk( compilation: &Compilation, chunk_ukey: &ChunkUkey, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let hooks = JsPlugin::get_compilation_hooks(compilation.id()); let chunk = compilation @@ -337,7 +336,7 @@ async fn render_startup( chunk_ukey: &ChunkUkey, _module: &ModuleIdentifier, render_source: &mut RenderSource, - runtime_template: &ChunkCodeTemplate, + runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { let chunk = compilation .build_chunk_graph_artifact diff --git a/crates/rspack_plugin_runtime/src/runtime_module/async_module.rs b/crates/rspack_plugin_runtime/src/runtime_module/async_module.rs index d551aecb0c65..e6dc5a6494e4 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/async_module.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/async_module.rs @@ -1,6 +1,6 @@ use rspack_core::{ - Compilation, RuntimeGlobals, RuntimeModule, RuntimeModuleGenerateContext, RuntimeTemplate, - RuntimeVariable, impl_runtime_module, + Compilation, RuntimeGlobals, RuntimeGlobalsRenderMode, RuntimeModule, + RuntimeModuleGenerateContext, RuntimeTemplate, RuntimeVariable, impl_runtime_module, }; static ASYNC_MODULE_TEMPLATE: &str = include_str!("runtime/async_module.ejs"); @@ -22,11 +22,15 @@ impl RuntimeModule for AsyncRuntimeModule { context: &RuntimeModuleGenerateContext<'_>, ) -> rspack_error::Result { let runtime_template = context.runtime_template; + let uses_lexical_runtime_globals = match runtime_template.render_mode() { + RuntimeGlobalsRenderMode::RspackLexical => true, + RuntimeGlobalsRenderMode::Webpack | RuntimeGlobalsRenderMode::RspackContext => false, + }; runtime_template.render( self.id(), Some(serde_json::json!({ "_module_cache": runtime_template.render_runtime_variable(&RuntimeVariable::ModuleCache), - "_uses_lexical_runtime_globals": runtime_template.uses_lexical_runtime_globals(), + "_uses_lexical_runtime_globals": uses_lexical_runtime_globals, })), ) } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/export_require.rs b/crates/rspack_plugin_runtime/src/runtime_module/export_require.rs index ef432325cca4..cfb0f034d212 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/export_require.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/export_require.rs @@ -12,10 +12,10 @@ pub struct ExportRequireRuntimeModule {} impl ExportRequireRuntimeModule { pub fn new(runtime_template: &RuntimeTemplate) -> Self { - let name = if runtime_template.runtime_module_prefix() == "rspack/runtime/" { - EXPORT_REQUIRE_RSPACK_RUNTIME_MODULE_ID - } else { + let name = if runtime_template.render_mode().is_legacy() { EXPORT_REQUIRE_RUNTIME_MODULE_ID + } else { + EXPORT_REQUIRE_RSPACK_RUNTIME_MODULE_ID }; Self::with_name(runtime_template, name) } diff --git a/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs index eba316b773dc..8fba07af569a 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/import_scripts_chunk_loading.rs @@ -63,7 +63,7 @@ impl ImportScriptsChunkLoadingRuntimeModule { &self, chunk: &Chunk, compilation: &Compilation, - runtime_template: &RuntimeCodeTemplate<'_>, + runtime_template: &RuntimeCodeTemplate, ) -> rspack_error::Result { let base_uri = if let Some(base_uri) = chunk .get_entry_options(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey) diff --git a/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs index 971c7dc35acc..5a0b4e34a5e6 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs @@ -109,7 +109,7 @@ impl JsonpChunkLoadingRuntimeModule { &self, chunk: &Chunk, compilation: &Compilation, - runtime_template: &RuntimeCodeTemplate<'_>, + runtime_template: &RuntimeCodeTemplate, ) -> String { let base_uri = chunk .get_entry_options(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey) diff --git a/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs index 8b1908f1b51e..1b75ec8372c7 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs @@ -108,7 +108,7 @@ impl ModuleChunkLoadingRuntimeModule { chunk: &Chunk, compilation: &Compilation, root_output_dir: &str, - runtime_template: &RuntimeCodeTemplate<'_>, + runtime_template: &RuntimeCodeTemplate, ) -> String { let base_uri = chunk .get_entry_options(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey) diff --git a/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs index 088875254ba5..f8ee3fa77e08 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/readfile_chunk_loading.rs @@ -73,7 +73,7 @@ impl ReadFileChunkLoadingRuntimeModule { chunk: &Chunk, compilation: &Compilation, root_output_dir: &str, - runtime_template: &RuntimeCodeTemplate<'_>, + runtime_template: &RuntimeCodeTemplate, ) -> String { let base_uri = chunk .get_entry_options(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey) diff --git a/crates/rspack_plugin_runtime/src/runtime_module/require_js_chunk_loading.rs b/crates/rspack_plugin_runtime/src/runtime_module/require_js_chunk_loading.rs index 837876be9dfa..8270ff3729e2 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/require_js_chunk_loading.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/require_js_chunk_loading.rs @@ -76,7 +76,7 @@ impl RequireChunkLoadingRuntimeModule { chunk: &Chunk, compilation: &Compilation, root_output_dir: &str, - runtime_template: &RuntimeCodeTemplate<'_>, + runtime_template: &RuntimeCodeTemplate, ) -> String { let base_uri = chunk .get_entry_options(&compilation.build_chunk_graph_artifact.chunk_group_by_ukey) diff --git a/crates/rspack_plugin_runtime/src/runtime_module/utils.rs b/crates/rspack_plugin_runtime/src/runtime_module/utils.rs index be61c01763ee..84f83f1df23f 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/utils.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/utils.rs @@ -2,7 +2,7 @@ use std::fmt::Write as _; use rspack_core::{ Chunk, ChunkLoading, ChunkUkey, Compilation, PathData, RuntimeCodeTemplate, RuntimeGlobals, - SourceType, + RuntimeGlobalsRenderMode, SourceType, chunk_graph_chunk::{ChunkId, ChunkIdSet}, get_js_chunk_filename_template, get_undo_path, }; @@ -63,16 +63,17 @@ pub fn stringify_chunks(chunks: &ChunkIdSet, value: u8) -> String { } pub fn render_hmr_runtime_state_expression( - runtime_template: &RuntimeCodeTemplate<'_>, + runtime_template: &RuntimeCodeTemplate, key: &str, ) -> String { - let state_prefix = if runtime_template.uses_lexical_runtime_globals() { - RuntimeGlobals::HMR_RUNTIME_STATE_PREFIX + let state_prefix = match runtime_template.render_mode() { + RuntimeGlobalsRenderMode::RspackLexical => RuntimeGlobals::HMR_RUNTIME_STATE_PREFIX .property_name() .expect("hmr runtime state prefix should have property name") - .to_string() - } else { - runtime_template.render_runtime_globals(&RuntimeGlobals::HMR_RUNTIME_STATE_PREFIX) + .to_string(), + RuntimeGlobalsRenderMode::Webpack | RuntimeGlobalsRenderMode::RspackContext => { + runtime_template.render_runtime_globals(&RuntimeGlobals::HMR_RUNTIME_STATE_PREFIX) + } }; format!("{state_prefix}_{key}") } diff --git a/crates/rspack_plugin_runtime/src/runtime_plugin.rs b/crates/rspack_plugin_runtime/src/runtime_plugin.rs index 25ac397641d2..bae9c43fd5d5 100644 --- a/crates/rspack_plugin_runtime/src/runtime_plugin.rs +++ b/crates/rspack_plugin_runtime/src/runtime_plugin.rs @@ -249,7 +249,9 @@ async fn runtime_requirements_in_tree( } } RuntimeGlobals::GET_CHUNK_SCRIPT_FILENAME => { - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); runtime_modules_to_add.push(( *chunk_ukey, GetChunkFilenameRuntimeModule::new( @@ -273,7 +275,9 @@ async fn runtime_requirements_in_tree( )); } RuntimeGlobals::GET_CHUNK_CSS_FILENAME => { - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); runtime_modules_to_add.push(( *chunk_ukey, GetChunkFilenameRuntimeModule::new( diff --git a/crates/rspack_plugin_wasm/src/loading_plugin.rs b/crates/rspack_plugin_wasm/src/loading_plugin.rs index c4981515a064..05d0658071f2 100644 --- a/crates/rspack_plugin_wasm/src/loading_plugin.rs +++ b/crates/rspack_plugin_wasm/src/loading_plugin.rs @@ -35,7 +35,9 @@ async fn fetch_compile_async_wasm_plugin_runtime_requirements_in_tree( return Ok(None); } - let runtime_template = compilation.runtime_template.create_runtime_code_template(); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); if runtime_requirements.contains(RuntimeGlobals::INSTANTIATE_WASM) { runtime_requirements_mut.insert(RuntimeGlobals::PUBLIC_PATH); runtime_modules_to_add.push((