From 2c6e7c9bfdaa36b51e93c9ae508c18921906317c Mon Sep 17 00:00:00 2001 From: harpsealjs Date: Thu, 30 Jul 2026 13:33:20 +0800 Subject: [PATCH] fix: avoid cjs rspack require parameter conflicts --- crates/rspack_core/src/runtime_template.rs | 83 +++++++++++-------- .../src/eval_dev_tool_module_plugin.rs | 6 ++ .../src/eval_source_map_dev_tool_plugin.rs | 6 ++ crates/rspack_plugin_esm_library/src/link.rs | 4 +- .../rspack_plugin_esm_library/src/render.rs | 1 - .../src/plugin/api_plugin.rs | 5 +- .../src/plugin/drive.rs | 6 +- .../src/plugin/mod.rs | 1 - .../src/plugin/runtime_context.rs | 1 - .../src/plugin/url_plugin.rs | 7 +- .../rspack_plugin_javascript/src/runtime.rs | 33 ++++---- crates/rspack_plugin_sri/src/config.rs | 4 +- crates/rspack_plugin_sri/src/lib.rs | 10 ++- crates/rspack_plugin_sri/src/runtime.rs | 29 ++++--- crates/rspack_plugin_sri/src/util.rs | 13 ++- .../runtimeModeSnapshot/case1.txt | 2 +- .../__snapshot__/runtimeModeSnapshot/f.js.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 6 +- .../__snapshots__/esm.snap.txt | 73 ++++++++++++++++ .../runtimeModeSnapshot/esm.snap.txt | 71 ++++++++++++++++ .../deconflict/cjs-rspack-require/index.js | 7 ++ .../deconflict/cjs-rspack-require/require.cjs | 3 + .../deconflict/cjs-rspack-require/value.cjs | 1 + .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 4 +- .../runtimeModeSnapshot/esm.snap.txt | 4 +- .../runtimeModeSnapshot/esm.snap.txt | 8 +- .../runtimeModeSnapshot/esm.snap.txt | 4 +- .../runtimeModeSnapshot/esm.snap.txt | 8 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 6 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../runtimeModeSnapshot/esm.snap.txt | 4 +- .../runtimeModeSnapshot/esm.snap.txt | 6 +- .../runtimeModeSnapshot/esm.snap.txt | 2 +- .../__snapshots__/esm.snap.txt | 30 +++++++ .../runtimeModeSnapshot/esm.snap.txt | 28 +++++++ .../runtime/modern-module-sri/index.js | 1 + .../modern-module-sri/rspack.config.js | 9 ++ .../runtime/modern-module-sri/test.config.js | 19 +++++ .../runtime/modern-module-sri/value.js | 1 + 47 files changed, 407 insertions(+), 119 deletions(-) create mode 100644 tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/esm.snap.txt create mode 100644 tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/runtimeModeSnapshot/esm.snap.txt create mode 100644 tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/index.js create mode 100644 tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/require.cjs create mode 100644 tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/value.cjs create mode 100644 tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/esm.snap.txt create mode 100644 tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/runtimeModeSnapshot/esm.snap.txt create mode 100644 tests/rspack-test/esmOutputCases/runtime/modern-module-sri/index.js create mode 100644 tests/rspack-test/esmOutputCases/runtime/modern-module-sri/rspack.config.js create mode 100644 tests/rspack-test/esmOutputCases/runtime/modern-module-sri/test.config.js create mode 100644 tests/rspack-test/esmOutputCases/runtime/modern-module-sri/value.js diff --git a/crates/rspack_core/src/runtime_template.rs b/crates/rspack_core/src/runtime_template.rs index 3859442dd424..bc1c6d39fe1f 100644 --- a/crates/rspack_core/src/runtime_template.rs +++ b/crates/rspack_core/src/runtime_template.rs @@ -362,7 +362,7 @@ impl RuntimeTemplate { RuntimeCodeTemplate::new( self.compiler_options.clone(), self.render_mode.runtime_module_render_mode(), - self.dojang.clone(), + Some(self.dojang.clone()), ) } @@ -371,7 +371,7 @@ impl RuntimeTemplate { RuntimeCodeTemplate::new( self.compiler_options.clone(), self.render_mode.chunk_render_mode(), - self.dojang.clone(), + None, ) } } @@ -868,11 +868,17 @@ impl ModuleCodeTemplate { } pub fn render_runtime_scope(&self) -> String { - let render_mode = match self.runtime_globals_render_mode { - RuntimeGlobalsRenderMode::Webpack => RuntimeGlobalsRenderMode::Webpack, - _ => RuntimeGlobalsRenderMode::RspackContext, - }; - get_runtime_globals_render_map(render_mode).render(&RuntimeGlobals::REQUIRE_SCOPE) + match self.runtime_globals_render_mode { + RuntimeGlobalsRenderMode::Webpack => { + WEBPACK_RUNTIME_GLOBALS.render(&RuntimeGlobals::REQUIRE_SCOPE) + } + RuntimeGlobalsRenderMode::RspackExport => { + self.runtime_globals.render(&RuntimeGlobals::REQUIRE) + } + RuntimeGlobalsRenderMode::RspackContext | RuntimeGlobalsRenderMode::RspackLexical => { + RSPACK_CONTEXT_RUNTIME_GLOBALS.render(&RuntimeGlobals::REQUIRE_SCOPE) + } + } } pub fn define_es_module_flag_statement(&mut self, exports_argument: ExportsArgument) -> String { @@ -1823,14 +1829,22 @@ pub struct RuntimeCodeTemplate { compiler_options: Arc, render_mode: RuntimeGlobalsRenderMode, runtime_globals: Arc, - dojang: Arc, + dojang: Option>, +} + +impl Debug for RuntimeCodeTemplate { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RuntimeCodeTemplate") + .field("render_mode", &self.render_mode) + .finish_non_exhaustive() + } } impl RuntimeCodeTemplate { fn new( compiler_options: Arc, render_mode: RuntimeGlobalsRenderMode, - dojang: Arc, + dojang: Option>, ) -> Self { Self { compiler_options, @@ -1897,6 +1911,26 @@ impl RuntimeCodeTemplate { "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} +}}"# + ) + } + } pub fn render(&self, key: &str, params: Option) -> Result { let mut render_params = Value::Object(Default::default()); @@ -1924,12 +1958,16 @@ impl RuntimeCodeTemplate { } } - if let Some((executer, file_content)) = self.dojang.templates.get(key) { + let dojang = self + .dojang + .as_ref() + .expect("chunk code templates cannot render runtime module templates"); + if let Some((executer, file_content)) = dojang.templates.get(key) { executer .render( &mut Context::new(render_params), - &self.dojang.templates, - &self.dojang.functions, + &dojang.templates, + &dojang.functions, file_content, #[cfg_attr( dylint_lib = "rspack_collection_hasher", @@ -1946,25 +1984,4 @@ impl RuntimeCodeTemplate { Err(error!("Runtime module: Template {key} is not found")) } } - - 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_devtool/src/eval_dev_tool_module_plugin.rs b/crates/rspack_plugin_devtool/src/eval_dev_tool_module_plugin.rs index faacef4f14bc..38a145d17438 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 @@ -1,3 +1,5 @@ +#![allow(clippy::too_many_arguments)] + use std::borrow::Cow; use cow_utils::CowUtils; @@ -85,9 +87,13 @@ async fn render_module_content( chunk_ukey: &ChunkUkey, module: &dyn Module, render_source: &mut RenderSource, + runtime_requirements: &mut RuntimeGlobals, _init_fragments: &mut ChunkInitFragments, runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { + if compilation.options.output.trusted_types.is_some() { + runtime_requirements.insert(RuntimeGlobals::CREATE_SCRIPT); + } let origin_source = render_source.source.clone(); if let Some(cached_source) = self.cache.get(&origin_source) { render_source.source = cached_source.value().clone(); 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 a21d09adea2e..58cb9f3db3df 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 @@ -1,3 +1,5 @@ +#![allow(clippy::too_many_arguments)] + use std::{borrow::Cow, sync::Arc}; use derive_more::Debug; @@ -95,9 +97,13 @@ async fn render_module_content( chunk: &ChunkUkey, module: &dyn Module, render_source: &mut RenderSource, + runtime_requirements: &mut RuntimeGlobals, _init_fragments: &mut ChunkInitFragments, runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { + if compilation.options.output.trusted_types.is_some() { + runtime_requirements.insert(RuntimeGlobals::CREATE_SCRIPT); + } let output_options = &compilation.options.output; let chunk = compilation .build_chunk_graph_artifact diff --git a/crates/rspack_plugin_esm_library/src/link.rs b/crates/rspack_plugin_esm_library/src/link.rs index b6f00054397c..8137b64ba36f 100644 --- a/crates/rspack_plugin_esm_library/src/link.rs +++ b/crates/rspack_plugin_esm_library/src/link.rs @@ -1498,6 +1498,7 @@ var {} = {{}}; let mut render_source = RenderSource { source: js_source.clone(), }; + let mut runtime_requirements = codegen_res.runtime_requirements; let mut chunk_init_fragments = vec![]; hooks @@ -1510,6 +1511,7 @@ var {} = {{}}; .expect("should have module") .as_ref(), &mut render_source, + &mut runtime_requirements, &mut chunk_init_fragments, runtime_template, ) @@ -1612,7 +1614,7 @@ var {} = {{}}; concate_info.has_ast = true; concate_info.source = Some(ReplaceSource::new(render_source.source.clone())); concate_info.internal_source = Some(render_source.source.clone()); - concate_info.runtime_requirements = codegen_res.runtime_requirements; + concate_info.runtime_requirements = runtime_requirements; concate_info.chunk_init_fragments = codegen_res .data .get::() diff --git a/crates/rspack_plugin_esm_library/src/render.rs b/crates/rspack_plugin_esm_library/src/render.rs index a5e97290ea87..217dd0a342ff 100644 --- a/crates/rspack_plugin_esm_library/src/render.rs +++ b/crates/rspack_plugin_esm_library/src/render.rs @@ -716,7 +716,6 @@ var {} = {{}}; } else { final_source }; - Ok(Some(RenderSource { source: final_source, })) diff --git a/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs index 85a8fefba09a..d7fef23784d5 100644 --- a/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs @@ -1,7 +1,9 @@ +#![allow(clippy::too_many_arguments)] + use rspack_core::{ ChunkInitFragments, ChunkUkey, Compilation, CompilationParams, CompilerCompilation, InitFragmentExt, InitFragmentKey, InitFragmentStage, Module, NormalInitFragment, Plugin, - RuntimeCodeTemplate, + RuntimeCodeTemplate, RuntimeGlobals, }; use rspack_error::Result; use rspack_hook::{plugin, plugin_hook}; @@ -34,6 +36,7 @@ async fn render_module_content( _chunk_ukey: &ChunkUkey, module: &dyn Module, _source: &mut RenderSource, + _runtime_requirements: &mut RuntimeGlobals, init_fragments: &mut ChunkInitFragments, _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { diff --git a/crates/rspack_plugin_javascript/src/plugin/drive.rs b/crates/rspack_plugin_javascript/src/plugin/drive.rs index 184469dfccbf..7bd75f053b09 100644 --- a/crates/rspack_plugin_javascript/src/plugin/drive.rs +++ b/crates/rspack_plugin_javascript/src/plugin/drive.rs @@ -1,6 +1,8 @@ +#![allow(clippy::too_many_arguments)] + use rspack_core::{ AssetInfo, BoxModule, Chunk, ChunkInitFragments, ChunkUkey, Compilation, Module, - ModuleIdentifier, RuntimeCodeTemplate, rspack_sources::BoxSource, + ModuleIdentifier, RuntimeCodeTemplate, RuntimeGlobals, rspack_sources::BoxSource, }; use rspack_hash::RspackHasher; use rspack_hook::define_hook; @@ -11,7 +13,7 @@ define_hook!(JavascriptModulesRenderChunk: Series(compilation: &Compilation, chu 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!(JavascriptModulesRenderModuleContent: Series(compilation: &Compilation, chunk_ukey: &ChunkUkey,module: &dyn Module, source: &mut RenderSource, runtime_requirements: &mut RuntimeGlobals, 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)); diff --git a/crates/rspack_plugin_javascript/src/plugin/mod.rs b/crates/rspack_plugin_javascript/src/plugin/mod.rs index 0cfa50497813..66a3e11430dd 100644 --- a/crates/rspack_plugin_javascript/src/plugin/mod.rs +++ b/crates/rspack_plugin_javascript/src/plugin/mod.rs @@ -896,7 +896,6 @@ var {} = {{}}; { rendered_module = source.clone(); }; - chunk_init_fragments.extend(fragments); chunk_init_fragments.extend(additional_fragments); let inner_strict = !all_strict && m.build_info().strict; diff --git a/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs b/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs index 4bf18f2c39ea..6db45bb4c4db 100644 --- a/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs +++ b/crates/rspack_plugin_javascript/src/plugin/runtime_context.rs @@ -801,7 +801,6 @@ impl JsPlugin { { rendered_module = source.clone(); }; - chunk_init_fragments.extend(fragments); chunk_init_fragments.extend(additional_fragments); let inner_strict = !all_strict && m.build_info().strict; diff --git a/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs index f45e42ff4760..3319d801cdeb 100644 --- a/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/url_plugin.rs @@ -1,10 +1,12 @@ +#![allow(clippy::too_many_arguments)] + use concat_string::concat_string; use rspack_core::{ ChunkInitFragments, ChunkUkey, CodeGenerationDataFilename, Compilation, CompilationParams, CompilerCompilation, DependencyId, JavascriptParserUrl, Module, ModuleType, NormalModuleFactoryParser, ParserAndGenerator, ParserOptions, PathData, Plugin, PublicPath, - RuntimeCodeTemplate, RuntimeSpec, SourceType, URLStaticMode, get_js_chunk_filename_template, - get_undo_path, + RuntimeCodeTemplate, RuntimeGlobals, RuntimeSpec, SourceType, URLStaticMode, + get_js_chunk_filename_template, get_undo_path, rspack_sources::{BoxSource, ReplaceSource, SourceExt}, }; use rspack_error::Result; @@ -196,6 +198,7 @@ async fn render_module_content( chunk_ukey: &ChunkUkey, module: &dyn Module, render_source: &mut RenderSource, + _runtime_requirements: &mut RuntimeGlobals, _init_fragments: &mut ChunkInitFragments, _runtime_template: &RuntimeCodeTemplate, ) -> Result<()> { diff --git a/crates/rspack_plugin_javascript/src/runtime.rs b/crates/rspack_plugin_javascript/src/runtime.rs index d85944a54822..882a79b92f15 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::{ ChunkGraph, ChunkInitFragments, ChunkKind, ChunkUkey, CodeGenerationPublicPathAutoReplace, - Compilation, Module, RuntimeCodeTemplate, RuntimeGlobals, RuntimeModuleGenerateContext, - SourceType, + Compilation, Module, RuntimeCodeTemplate, RuntimeGlobals, RuntimeGlobalsRenderMode, + RuntimeModuleGenerateContext, SourceType, chunk_graph_chunk::ChunkIdSet, get_undo_path, render_runtime_module_source, rspack_sources::{ @@ -136,6 +136,7 @@ pub async fn render_module( Some(fragments) => fragments.clone(), None => ChunkInitFragments::default(), }; + let mut render_runtime_requirements = code_gen_result.runtime_requirements; let mut render_source = if code_gen_result .data @@ -191,6 +192,7 @@ pub async fn render_module( chunk_ukey, module, &mut render_source, + &mut render_runtime_requirements, &mut module_chunk_init_fragments, runtime_template, ) @@ -214,21 +216,16 @@ pub async fn render_module( let need_module = runtime_requirements.is_some_and(|r| r.contains(RuntimeGlobals::MODULE)); let need_exports = runtime_requirements.is_some_and(|r| r.contains(RuntimeGlobals::EXPORTS)); - let need_require = runtime_requirements.is_some_and(|r| { - r.contains(RuntimeGlobals::REQUIRE) - || r.contains(RuntimeGlobals::REQUIRE_SCOPE) - || (compilation.options.experiments.runtime_mode == RuntimeMode::Rspack - && !r.renderable_require_scope().is_empty()) - }); - let need_require = if need_require { - render_source - .source - .source() - .into_string_lossy() - .contains(&runtime_template.render_runtime_argument()) - } else { - need_require - }; + let need_require = runtime_template.render_mode() != RuntimeGlobalsRenderMode::RspackExport + && (render_runtime_requirements.contains(RuntimeGlobals::REQUIRE) + || render_runtime_requirements.contains(RuntimeGlobals::REQUIRE_SCOPE) + || !render_runtime_requirements + .renderable_require_scope() + .is_empty()); + let module_runtime_scope = compilation + .runtime_template + .create_module_code_template() + .render_runtime_scope(); let mut args = Vec::new(); if need_module || need_exports || need_require { @@ -250,7 +247,7 @@ pub async fn render_module( }); } if need_require { - args.push(runtime_template.render_runtime_argument()); + args.push(module_runtime_scope); } let mut container_sources = ConcatSource::default(); diff --git a/crates/rspack_plugin_sri/src/config.rs b/crates/rspack_plugin_sri/src/config.rs index 7e877d354422..df685d343339 100644 --- a/crates/rspack_plugin_sri/src/config.rs +++ b/crates/rspack_plugin_sri/src/config.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use derive_more::Debug; use futures::future::BoxFuture; -use rspack_core::{CrossOriginLoading, ModuleCodeTemplate}; +use rspack_core::CrossOriginLoading; use rspack_error::Result; use rspack_fs::WritableFileSystem; use rspack_paths::Utf8PathBuf; @@ -54,7 +54,7 @@ pub struct SRICompilationContext { pub fs: ArcFs, pub output_path: Utf8PathBuf, pub cross_origin_loading: CrossOriginLoading, - pub runtime_template: ModuleCodeTemplate, + pub runtime_require_name: String, } pub struct IntegrityCallbackData { diff --git a/crates/rspack_plugin_sri/src/lib.rs b/crates/rspack_plugin_sri/src/lib.rs index cd6ca21a9c79..13736ac96115 100644 --- a/crates/rspack_plugin_sri/src/lib.rs +++ b/crates/rspack_plugin_sri/src/lib.rs @@ -17,7 +17,7 @@ use html::{alter_asset_tag_groups, before_asset_tag_generation}; pub use integrity::SubresourceIntegrityHashFunction; use rspack_core::{ ChunkLoading, ChunkLoadingType, Compilation, CompilationId, CompilationParams, - CompilerThisCompilation, CrossOriginLoading, Plugin, + CompilerThisCompilation, CrossOriginLoading, Plugin, RuntimeGlobals, }; use rspack_error::{Diagnostic, Result}; use rspack_hook::{plugin, plugin_hook}; @@ -119,11 +119,17 @@ async fn handle_compilation( compilation: &mut Compilation, _params: &mut CompilationParams, ) -> Result<()> { + let runtime_require_name = { + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); + runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE) + }; let ctx = SRICompilationContext { fs: compilation.output_filesystem.clone(), output_path: compilation.options.output.path.clone(), cross_origin_loading: compilation.options.output.cross_origin_loading.clone(), - runtime_template: compilation.runtime_template.create_module_code_template(), + runtime_require_name, }; SubresourceIntegrityPlugin::set_compilation_sri_context(compilation.id(), ctx); diff --git a/crates/rspack_plugin_sri/src/runtime.rs b/crates/rspack_plugin_sri/src/runtime.rs index 565b1c4610b4..a82a2fba99f3 100644 --- a/crates/rspack_plugin_sri/src/runtime.rs +++ b/crates/rspack_plugin_sri/src/runtime.rs @@ -81,20 +81,21 @@ impl RuntimeModule for SRIHashVariableRuntimeModule { let module_graph = compilation.get_module_graph(); - let runtime_template = compilation.runtime_template.create_module_code_template(); + let runtime_template = context.runtime_template; + let runtime_require_name = runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE); let source_types = vec![ ( SourceType::JavaScript, - get_hash_variable(&runtime_template, SourceType::JavaScript), + get_hash_variable(&runtime_require_name, SourceType::JavaScript), ), ( SourceType::Css, - get_hash_variable(&runtime_template, SourceType::Css), + get_hash_variable(&runtime_require_name, SourceType::Css), ), ( SourceType::Custom("css/mini-extract".into()), get_hash_variable( - &runtime_template, + &runtime_require_name, SourceType::Custom("css/mini-extract".into()), ), ), @@ -197,7 +198,7 @@ pub async fn create_script(&self, mut data: CreateScriptData) -> Result( mut data: CreateLinkData<'a>, ) -> Result> { let ctx = SubresourceIntegrityPlugin::get_compilation_sri_context(compilation.id()); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); + let runtime_require_name = runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE); if data.code.contains("loadingAttribute") { data.code = add_attribute( "link", - &get_hash_variable(&ctx.runtime_template, SourceType::Css), + &get_hash_variable(&runtime_require_name, SourceType::Css), &data.code, &ctx.cross_origin_loading, ); @@ -222,7 +227,7 @@ pub async fn create_link<'a>( data.code = add_attribute( "linkTag", &get_hash_variable( - &ctx.runtime_template, + &runtime_require_name, SourceType::Custom("css/mini-extract".into()), ), &data.code, @@ -240,16 +245,20 @@ pub async fn link_preload<'a>( mut data: LinkPreloadData<'a>, ) -> Result> { let ctx = SubresourceIntegrityPlugin::get_compilation_sri_context(compilation.id()); + let runtime_template = compilation + .runtime_template + .create_runtime_module_code_template(); + let runtime_require_name = runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE); if data.code.contains(".as = \"style\"") { data.code = add_attribute( "link", (if data.code.contains(".miniCssF") { get_hash_variable( - &ctx.runtime_template, + &runtime_require_name, SourceType::Custom("css/mini-extract".into()), ) } else { - get_hash_variable(&ctx.runtime_template, SourceType::Css) + get_hash_variable(&runtime_require_name, SourceType::Css) }) .as_str(), &data.code, @@ -258,7 +267,7 @@ pub async fn link_preload<'a>( } else { data.code = add_attribute( "link", - &get_hash_variable(&ctx.runtime_template, SourceType::JavaScript), + &get_hash_variable(&runtime_require_name, SourceType::JavaScript), &data.code, &ctx.cross_origin_loading, ); diff --git a/crates/rspack_plugin_sri/src/util.rs b/crates/rspack_plugin_sri/src/util.rs index b55b213e5867..9280f0711398 100644 --- a/crates/rspack_plugin_sri/src/util.rs +++ b/crates/rspack_plugin_sri/src/util.rs @@ -2,8 +2,7 @@ use std::{borrow::Cow, sync::LazyLock}; use cow_utils::CowUtils; use rspack_core::{ - AssetInfo, ChunkGroupUkey, ChunkUkey, Compilation, ManifestAssetType, ModuleCodeTemplate, - RuntimeGlobals, SourceType, + AssetInfo, ChunkGroupUkey, ChunkUkey, Compilation, ManifestAssetType, SourceType, }; use rspack_util::fx_hash::FxIndexSet; @@ -19,14 +18,12 @@ pub static PLACEHOLDER_REGEX: LazyLock = LazyLock::new(|| { .expect("should initialize `Regex`") }); -pub fn get_hash_variable(runtime_template: &ModuleCodeTemplate, source_type: SourceType) -> String { - let require_name = - runtime_template.render_runtime_globals_without_adding(&RuntimeGlobals::REQUIRE); +pub fn get_hash_variable(runtime_require_name: &str, source_type: SourceType) -> String { match source_type { - SourceType::JavaScript => format!("{require_name}.sriHashes"), - SourceType::Css => format!("{require_name}.sriCssHashes"), + SourceType::JavaScript => format!("{runtime_require_name}.sriHashes"), + SourceType::Css => format!("{runtime_require_name}.sriCssHashes"), SourceType::Custom(t) if t == "css/mini-extract" => { - format!("{require_name}.sriExtractCssHashes") + format!("{runtime_require_name}.sriExtractCssHashes") } _ => unreachable!(), } diff --git a/tests/rspack-test/configCases/externals/reexport-star/__snapshot__/runtimeModeSnapshot/case1.txt b/tests/rspack-test/configCases/externals/reexport-star/__snapshot__/runtimeModeSnapshot/case1.txt index 1d24bfd38554..73a01befb2e6 100644 --- a/tests/rspack-test/configCases/externals/reexport-star/__snapshot__/runtimeModeSnapshot/case1.txt +++ b/tests/rspack-test/configCases/externals/reexport-star/__snapshot__/runtimeModeSnapshot/case1.txt @@ -2,7 +2,7 @@ import { rspackRequire, moduleFactories, definePropertyGetters, makeNamespaceObj import * as __rspack_external_external1_alias_dd38afe7 from "external1-alias"; import * as __rspack_external_external2_alias_d6100a5a from "external2-alias"; moduleFactories.add({ -42(__unused_rspack_module, exports, rspackRequire) { +42(__unused_rspack_module, exports) { makeNamespaceObject(exports); /* import */ var external1__rspack_import_0 = rspackRequire(322); diff --git a/tests/rspack-test/configCases/library/modern-module-force-concaten/__snapshot__/runtimeModeSnapshot/f.js.txt b/tests/rspack-test/configCases/library/modern-module-force-concaten/__snapshot__/runtimeModeSnapshot/f.js.txt index c843fc9bb67c..d632a10d2ede 100644 --- a/tests/rspack-test/configCases/library/modern-module-force-concaten/__snapshot__/runtimeModeSnapshot/f.js.txt +++ b/tests/rspack-test/configCases/library/modern-module-force-concaten/__snapshot__/runtimeModeSnapshot/f.js.txt @@ -6,7 +6,7 @@ moduleFactories.add({ module.exports = __rspack_createRequire_require("path"); }, -227(module, __unused_rspack_exports, rspackRequire) { +227(module) { const path = rspackRequire(928) module.exports = path.sep diff --git a/tests/rspack-test/esmOutputCases/basic/side-effect-only-connections/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/basic/side-effect-only-connections/__snapshots__/runtimeModeSnapshot/esm.snap.txt index bbbeeccaec27..7d9b9717dc11 100644 --- a/tests/rspack-test/esmOutputCases/basic/side-effect-only-connections/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/basic/side-effect-only-connections/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -5,7 +5,7 @@ moduleFactories.add({ /*!******************!*\ !*** ./index.js ***! \******************/ -(__unused_rspack_module, __unused_rspack_exports, rspackRequire) { +() { it('should has connection to lib only in closure', () => { const { foo } = rspackRequire(/*! ./lib */ "./lib.js") expect(foo()).toBe(42) diff --git a/tests/rspack-test/esmOutputCases/basic/tree-shaking/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/basic/tree-shaking/__snapshots__/runtimeModeSnapshot/esm.snap.txt index f126701590a1..7b861c3f3c5c 100644 --- a/tests/rspack-test/esmOutputCases/basic/tree-shaking/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/basic/tree-shaking/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -6,7 +6,7 @@ moduleFactories.add({ /*!****************!*\ !*** ./cjs.js ***! \****************/ -(__unused_rspack_module, __unused_rspack_exports, rspackRequire) { +() { /* import */ var _use_other__rspack_import_0 = rspackRequire(/*! ./use-other */ "./use-other.js"); /* import */ var _use_other__rspack_import_0_default = /*#__PURE__*/compatGetDefaultExport(_use_other__rspack_import_0); @@ -20,7 +20,7 @@ console.log.bind((rspackRequire(/*! fs */ "fs")/* .readFile */.readFile)) /*!******************!*\ !*** ./index.js ***! \******************/ -(module, exports, rspackRequire) { +(module, exports) { makeNamespaceObject(exports); /* import */ var _cjs__rspack_import_0 = rspackRequire(/*! ./cjs */ "./cjs.js"); /* module decorator */ module = esmModuleDecorator(module); @@ -37,7 +37,7 @@ console.log.bind(module) /*!**********************!*\ !*** ./use-other.js ***! \**********************/ -(__unused_rspack_module, __unused_rspack_exports, rspackRequire) { +() { // use export writeFile console.log.bind((rspackRequire(/*! fs */ "fs")/* .writeFile */.writeFile)) diff --git a/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/esm.snap.txt b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/esm.snap.txt new file mode 100644 index 000000000000..784165cfe724 --- /dev/null +++ b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/esm.snap.txt @@ -0,0 +1,73 @@ +```mjs title=main.mjs +import { __webpack_require__ } from "./runtime.mjs"; + +__webpack_require__.add({ +"./require.cjs" +/*!*********************!*\ + !*** ./require.cjs ***! + \*********************/ +(module, __unused_rspack_exports, __webpack_require__) { +const rspackRequire = __webpack_require__(/*! ./value.cjs */ "./value.cjs"); + +module.exports = rspackRequire; + + +}, +"./value.cjs" +/*!*******************!*\ + !*** ./value.cjs ***! + \*******************/ +(module) { +module.exports = 42; + + +}, +}); +// ./index.js +__webpack_require__("./require.cjs"); + + +const value = __webpack_require__("./require.cjs"); + +it("should avoid a CJS rspackRequire factory parameter conflict", () => { + expect(value).toBe(42); +}); + +export {}; + +``` + +```mjs title=runtime.mjs + +var __webpack_modules__ = {}; +// The module cache +var __webpack_module_cache__ = {}; +// The require function +function __webpack_require__(moduleId) { +// Check if module is in cache +var cachedModule = __webpack_module_cache__[moduleId]; +if (cachedModule !== undefined) { +return cachedModule.exports; +} +// Create a new module (and put it into the cache) +var module = (__webpack_module_cache__[moduleId] = { +exports: {} +}); +// Execute the module function +__webpack_modules__[moduleId](module, module.exports, __webpack_require__); + +// Return the exports of the module +return module.exports; +} +// expose the modules object (__webpack_modules__) +__webpack_require__.m = __webpack_modules__; + +// webpack/runtime/esm_register_module +(() => { +__webpack_require__.add = function registerModules(modules) { Object.assign(__webpack_require__.m, modules) } + +})(); + +export { __webpack_require__ }; + +``` \ No newline at end of file diff --git a/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/runtimeModeSnapshot/esm.snap.txt new file mode 100644 index 000000000000..857f4cfb8302 --- /dev/null +++ b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -0,0 +1,71 @@ +```mjs title=main.mjs +import { rspackRequire, moduleFactories } from "./runtime.mjs"; +moduleFactories.add({ +"./require.cjs" +/*!*********************!*\ + !*** ./require.cjs ***! + \*********************/ +(module) { +const __nested_rspack_require_6_19__ = rspackRequire(/*! ./value.cjs */ "./value.cjs"); + +module.exports = __nested_rspack_require_6_19__; + + +}, +"./value.cjs" +/*!*******************!*\ + !*** ./value.cjs ***! + \*******************/ +(module) { +module.exports = 42; + + +}, +}); +// ./index.js +rspackRequire("./require.cjs"); + + +const value = rspackRequire("./require.cjs"); + +it("should avoid a CJS rspackRequire factory parameter conflict", () => { + expect(value).toBe(42); +}); + +export {}; + +``` + +```mjs title=runtime.mjs + +var modules = {}; +// The module cache +var moduleCache = {}; +// The require function +function rspackRequire(moduleId) { +// Check if module is in cache +var cachedModule = moduleCache[moduleId]; +if (cachedModule !== undefined) { +return cachedModule.exports; +} +// Create a new module (and put it into the cache) +var module = (moduleCache[moduleId] = { +exports: {} +}); +// Execute the module function +modules[moduleId](module, module.exports, rspackRequire); + +// Return the exports of the module +return module.exports; +} +export { rspackRequire }; +// expose the modules object (modules) +var moduleFactories = modules; +export { moduleFactories }; + +// rspack/runtime/esm_register_module +moduleFactories.add = function registerModules(modules) { Object.assign(moduleFactories, modules) } +; + + +``` \ No newline at end of file diff --git a/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/index.js b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/index.js new file mode 100644 index 000000000000..6d5409c1cd0c --- /dev/null +++ b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/index.js @@ -0,0 +1,7 @@ +import "./require.cjs"; + +const value = __webpack_require__("./require.cjs"); + +it("should avoid a CJS rspackRequire factory parameter conflict", () => { + expect(value).toBe(42); +}); diff --git a/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/require.cjs b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/require.cjs new file mode 100644 index 000000000000..7c545fbbdaa6 --- /dev/null +++ b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/require.cjs @@ -0,0 +1,3 @@ +const rspackRequire = require("./value.cjs"); + +module.exports = rspackRequire; diff --git a/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/value.cjs b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/value.cjs new file mode 100644 index 000000000000..888cae37af95 --- /dev/null +++ b/tests/rspack-test/esmOutputCases/deconflict/cjs-rspack-require/value.cjs @@ -0,0 +1 @@ +module.exports = 42; diff --git a/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-async-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-async-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt index bab7ed01ba21..877e5fa6aec2 100644 --- a/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-async-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-async-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -5,7 +5,7 @@ moduleFactories.add({ /*!********************!*\ !*** ./dynamic.js ***! \********************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { const shared = rspackRequire(/*! ./shared */ "./shared.js"); exports.value = shared.base + 41; diff --git a/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-entry-export/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-entry-export/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 2bcf4dff29d4..1db15d27b463 100644 --- a/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-entry-export/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs-runtime-chunk-false-entry-export/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -7,7 +7,7 @@ moduleFactories.add({ /*!********************!*\ !*** ./dynamic.js ***! \********************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { const shared = rspackRequire(/*! ./shared */ "./shared.js"); exports.value = shared.base + 41; diff --git a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-css/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-css/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 2cfa00a20570..1c4024e612db 100644 --- a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-css/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-css/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -40,7 +40,7 @@ moduleFactories.add({ /*!**********************************************************************************************************************************************!*\ !*** ./modules|lazy|/^\.\/.*\.js$/|referencedExports: default|groupOptions: {fetchPriority: high,}|namespace object|importPhase: evaluation ***! \**********************************************************************************************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { var map = { "./a.js": [ "./modules/a.js", @@ -72,7 +72,7 @@ module.exports = __rspack_async_context; /*!*******************************************************************!*\ !*** ./modules|lazy|nonrecursive|./modules/*.js|namespace object ***! \*******************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { module.exports = { diff --git a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-lazy/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-lazy/__snapshots__/runtimeModeSnapshot/esm.snap.txt index fced10de267e..3f8b758862c2 100644 --- a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-lazy/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-lazy/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -51,7 +51,7 @@ moduleFactories.add({ /*!**************************************************************************************************************************!*\ !*** ./modules|lazy|/^\.\/.*\.js$/|referencedExports: default|groupOptions: {}|namespace object|importPhase: evaluation ***! \**************************************************************************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { var map = { "./a.js": [ "./modules/a.js", @@ -89,7 +89,7 @@ module.exports = __rspack_async_context; /*!*******************************************************************!*\ !*** ./modules|lazy|nonrecursive|./modules/*.js|namespace object ***! \*******************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { module.exports = { diff --git a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt index e78bb11feff3..fef1c84d3145 100644 --- a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-chunk/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -7,7 +7,7 @@ moduleFactories.add({ /*!**********************!*\ !*** ./modules/a.js ***! \**********************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { makeNamespaceObject(exports); /* import */ var _shared__rspack_import_0 = rspackRequire(/*! ../shared */ "./shared.js"); @@ -35,7 +35,7 @@ moduleFactories.add({ /*!**********************!*\ !*** ./modules/b.js ***! \**********************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { makeNamespaceObject(exports); /* import */ var _shared__rspack_import_0 = rspackRequire(/*! ../shared */ "./shared.js"); @@ -61,7 +61,7 @@ moduleFactories.add({ /*!**************************************************************************************************************************!*\ !*** ./modules|lazy|/^\.\/.*\.js$/|referencedExports: default|groupOptions: {}|namespace object|importPhase: evaluation ***! \**************************************************************************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { var map = { "./a.js": [ "./modules/a.js", @@ -103,7 +103,7 @@ module.exports = __rspack_async_context; /*!*******************************************************************!*\ !*** ./modules|lazy|nonrecursive|./modules/*.js|namespace object ***! \*******************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { module.exports = { diff --git a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 267ba837c8d9..5c63825fde5e 100644 --- a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -51,7 +51,7 @@ moduleFactories.add({ /*!***********************************************************************!*\ !*** ./modules-a|lazy|nonrecursive|./modules-a/*.js|namespace object ***! \***********************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { module.exports = { @@ -82,7 +82,7 @@ moduleFactories.add({ /*!***********************************************************************!*\ !*** ./modules-b|lazy|nonrecursive|./modules-b/*.js|namespace object ***! \***********************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { module.exports = { diff --git a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-prefetch-preload/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-prefetch-preload/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 749d47f5fb36..b639bff46f1b 100644 --- a/tests/rspack-test/esmOutputCases/dynamic-import/import-context-prefetch-preload/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/dynamic-import/import-context-prefetch-preload/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -27,7 +27,7 @@ moduleFactories.add({ /*!**********************!*\ !*** ./modules/b.js ***! \**********************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { makeNamespaceObject(exports); import("./c.mjs").then(rspackRequire.bind(rspackRequire, /*! ./c */ "./modules/c.js")); @@ -73,7 +73,7 @@ moduleFactories.add({ /*!*******************************************************************************************************************************************!*\ !*** ./modules|lazy|/^\.\/.*\.js$/|referencedExports: default|groupOptions: {prefetchOrder: 0,}|namespace object|importPhase: evaluation ***! \*******************************************************************************************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { var map = { "./a.js": [ "./modules/a.js", @@ -117,7 +117,7 @@ module.exports = __rspack_async_context; /*!******************************************************************************************************************************************!*\ !*** ./modules|lazy|/^\.\/.*\.js$/|referencedExports: default|groupOptions: {preloadOrder: 0,}|namespace object|importPhase: evaluation ***! \******************************************************************************************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { var map = { "./a.js": [ "./modules/a.js", @@ -161,7 +161,7 @@ module.exports = __rspack_async_context; /*!*******************************************************************!*\ !*** ./modules|lazy|nonrecursive|./modules/*.js|namespace object ***! \*******************************************************************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { module.exports = { diff --git a/tests/rspack-test/esmOutputCases/externals/dedup-external-imports-mixed/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/externals/dedup-external-imports-mixed/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 4c17e92c2c84..89c975c8fbf2 100644 --- a/tests/rspack-test/esmOutputCases/externals/dedup-external-imports-mixed/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/externals/dedup-external-imports-mixed/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -16,7 +16,7 @@ module.exports = __rspack_external_fs; /*!**************************!*\ !*** ./cjs-consumer.cjs ***! \**************************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { // CJS module - will NOT be scope-hoisted, causing its fs dep // to go through init fragment path instead of raw_import_stmts const fs = rspackRequire(/*! fs */ "fs?94de") diff --git a/tests/rspack-test/esmOutputCases/externals/esm-node-target-alias/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/externals/esm-node-target-alias/__snapshots__/runtimeModeSnapshot/esm.snap.txt index fd844ed6ae0d..70b559971ef1 100644 --- a/tests/rspack-test/esmOutputCases/externals/esm-node-target-alias/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/externals/esm-node-target-alias/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -26,7 +26,7 @@ module.exports = __rspack_createRequire_require("node:url"); /*!**************************!*\ !*** ./cjs-consumer.cjs ***! \**************************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { // CJS require of "module" type external — should be downgraded to node-commonjs const nodePath = rspackRequire(/*! node:fs */ "node:fs?435f"); exports.n = nodePath.resolve; diff --git a/tests/rspack-test/esmOutputCases/externals/runtime-decide/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/externals/runtime-decide/__snapshots__/runtimeModeSnapshot/esm.snap.txt index aac9178c5b48..12a68d29d854 100644 --- a/tests/rspack-test/esmOutputCases/externals/runtime-decide/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/externals/runtime-decide/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -21,7 +21,7 @@ def(exports) /*!***************************!*\ !*** ./runtime-decide.js ***! \***************************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { /* import */ var _dynamic_exports__rspack_import_0 = rspackRequire(/*! ./dynamic-exports */ "./dynamic-exports.js"); /* import */ var _dynamic_exports__rspack_import_0_default = /*#__PURE__*/compatGetDefaultExport(_dynamic_exports__rspack_import_0); if(hasOwnProperty(_dynamic_exports__rspack_import_0, "readFile")) definePropertyGetters(exports, { readFile: function() { return _dynamic_exports__rspack_import_0.readFile; } }); diff --git a/tests/rspack-test/esmOutputCases/interop/runtime-module-variable-conflict/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/interop/runtime-module-variable-conflict/__snapshots__/runtimeModeSnapshot/esm.snap.txt index f5ae3b6b8ca1..3f932318f32b 100644 --- a/tests/rspack-test/esmOutputCases/interop/runtime-module-variable-conflict/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/interop/runtime-module-variable-conflict/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -73,7 +73,7 @@ function index_createFakeNamespaceObject() { const index_moduleCache = "application"; const index_modules = "application"; -const index_rspackRequire = "application"; +const __nested_rspack_require_219_232__ = "application"; const index_rspack_get_mini_css_chunk_filename = "application"; it("should avoid conflicts with runtime module variables", () => { @@ -82,12 +82,12 @@ it("should avoid conflicts with runtime module variables", () => { expect(index_createFakeNamespaceObject()).toBe("application"); expect(index_moduleCache).toBe("application"); expect(index_modules).toBe("application"); - expect(index_rspackRequire).toBe("application"); + expect(__nested_rspack_require_219_232__).toBe("application"); expect(index_rspack_get_mini_css_chunk_filename).toBe("application"); }); -export { index_createFakeNamespaceObject as createFakeNamespaceObject, index_getProto as getProto, index_moduleCache as moduleCache, index_modules as modules, index_rspackRequire as rspackRequire, index_rspack_get_mini_css_chunk_filename as __rspack_get_mini_css_chunk_filename }; +export { __nested_rspack_require_219_232__ as rspackRequire, index_createFakeNamespaceObject as createFakeNamespaceObject, index_getProto as getProto, index_moduleCache as moduleCache, index_modules as modules, index_rspack_get_mini_css_chunk_filename as __rspack_get_mini_css_chunk_filename }; ``` \ No newline at end of file diff --git a/tests/rspack-test/esmOutputCases/preserve-modules/module-external-remapping/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/preserve-modules/module-external-remapping/__snapshots__/runtimeModeSnapshot/esm.snap.txt index fb24c77b1cf2..4d3b55e4d020 100644 --- a/tests/rspack-test/esmOutputCases/preserve-modules/module-external-remapping/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/preserve-modules/module-external-remapping/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -141,7 +141,7 @@ moduleFactories.add({ /*!************************!*\ !*** ./src/wrapped.js ***! \************************/ -(module, exports, rspackRequire) { +(module, exports) { /* import */ var node_events__rspack_import_0 = rspackRequire(/*! node:events */ "node:events?df85"); /* module decorator */ module = esmModuleDecorator(module); diff --git a/tests/rspack-test/esmOutputCases/preserve-modules/re-export-module-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/preserve-modules/re-export-module-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 285505236b97..57822b7aef9f 100644 --- a/tests/rspack-test/esmOutputCases/preserve-modules/re-export-module-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/preserve-modules/re-export-module-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -132,7 +132,7 @@ moduleFactories.add({ /*!************************!*\ !*** ./src/wrapped.js ***! \************************/ -(module, exports, rspackRequire) { +(module, exports) { /* import */ var fs__rspack_import_0 = rspackRequire(/*! fs */ "fs?2159"); /* module decorator */ module = esmModuleDecorator(module); diff --git a/tests/rspack-test/esmOutputCases/preserve-modules/re-export-node-commonjs-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/preserve-modules/re-export-node-commonjs-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 60dbe9cbc6ea..05ab84627e34 100644 --- a/tests/rspack-test/esmOutputCases/preserve-modules/re-export-node-commonjs-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/preserve-modules/re-export-node-commonjs-external-hoist-mix/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -149,7 +149,7 @@ moduleFactories.add({ /*!************************!*\ !*** ./src/wrapped.js ***! \************************/ -(module, exports, rspackRequire) { +(module, exports) { /* import */ var fs__rspack_import_0 = rspackRequire(/*! fs */ "fs"); /* import */ var fs__rspack_import_0_default = /*#__PURE__*/compatGetDefaultExport(fs__rspack_import_0); /* module decorator */ module = esmModuleDecorator(module); diff --git a/tests/rspack-test/esmOutputCases/re-exports/cjs-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/re-exports/cjs-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 3293ae80d610..c24e9f4822ad 100644 --- a/tests/rspack-test/esmOutputCases/re-exports/cjs-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/re-exports/cjs-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -14,7 +14,7 @@ exports.bar = 2 /*!****************!*\ !*** ./foo.js ***! \****************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { makeNamespaceObject(exports); /* import */ var _bar__rspack_import_0 = rspackRequire(/*! ./bar */ "./bar.js"); const foo = 1 @@ -32,7 +32,7 @@ definePropertyGetters(exports, { /*!******************!*\ !*** ./index.js ***! \******************/ -(module, __unused_rspack_exports, rspackRequire) { +(module) { module.exports = rspackRequire(/*! ./foo */ "./foo.js") it('should have correct output for entry re-exports', async () => { diff --git a/tests/rspack-test/esmOutputCases/re-exports/deep-re-exports-esm-2/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/re-exports/deep-re-exports-esm-2/__snapshots__/runtimeModeSnapshot/esm.snap.txt index c0fb685d29c6..a72cdeec36a2 100644 --- a/tests/rspack-test/esmOutputCases/re-exports/deep-re-exports-esm-2/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/re-exports/deep-re-exports-esm-2/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -7,7 +7,7 @@ moduleFactories.add({ /*!****************!*\ !*** ./lib.js ***! \****************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { makeNamespaceObject(exports); /* import */ var fs__rspack_import_0 = rspackRequire(/*! fs */ "fs"); @@ -36,7 +36,7 @@ definePropertyGetters(exports, { /*!*****************!*\ !*** ./lib2.js ***! \*****************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { makeNamespaceObject(exports); /* import */ var path__rspack_import_0 = rspackRequire(/*! path */ "path"); @@ -64,7 +64,7 @@ definePropertyGetters(exports, { /*!*****************!*\ !*** ./lib3.js ***! \*****************/ -(__unused_rspack_module, exports, rspackRequire) { +(__unused_rspack_module, exports) { /* import */ var fs__rspack_import_0 = rspackRequire(/*! fs */ "fs"); const lib3 = 42 diff --git a/tests/rspack-test/esmOutputCases/re-exports/wrapped-esm-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/re-exports/wrapped-esm-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt index 898ed720a97e..00500775a4d0 100644 --- a/tests/rspack-test/esmOutputCases/re-exports/wrapped-esm-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt +++ b/tests/rspack-test/esmOutputCases/re-exports/wrapped-esm-entry/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -6,7 +6,7 @@ moduleFactories.add({ /*!******************!*\ !*** ./index.js ***! \******************/ -(module, exports, rspackRequire) { +(module, exports) { makeNamespaceObject(exports); /* import */ var fs__rspack_import_0 = rspackRequire(/*! fs */ "fs"); diff --git a/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/esm.snap.txt b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/esm.snap.txt new file mode 100644 index 000000000000..81f1b286d65d --- /dev/null +++ b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/esm.snap.txt @@ -0,0 +1,30 @@ +```mjs title=main.mjs +// ./index.js +const value = import("./value.mjs"); + +export { value }; + +``` + +```mjs title=runtime.mjs +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/sri_hash_variable +(() => { + + __webpack_require__.sriHashes = {"value": "sha384-n/vSaOHnKSkGM5h7v+v8wRPJlDOhVXbgjK6iYxj8/sWl7re7g0lRNVYd7Gs6mPAy"}; + +})(); + +export { __webpack_require__ }; + +``` + +```mjs title=value.mjs +// ./value.js +/* export default */ const value = (42); + +export default value; + +``` \ No newline at end of file diff --git a/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/runtimeModeSnapshot/esm.snap.txt b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/runtimeModeSnapshot/esm.snap.txt new file mode 100644 index 000000000000..325adbad0430 --- /dev/null +++ b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/__snapshots__/runtimeModeSnapshot/esm.snap.txt @@ -0,0 +1,28 @@ +```mjs title=main.mjs +// ./index.js +const value = import("./value.mjs"); + +export { value }; + +``` + +```mjs title=runtime.mjs +// The require scope +var rspackRequire = {}; +export { rspackRequire }; + +// rspack/runtime/sri_hash_variable + + rspackRequire.sriHashes = {"value": "sha384-n/vSaOHnKSkGM5h7v+v8wRPJlDOhVXbgjK6iYxj8/sWl7re7g0lRNVYd7Gs6mPAy"}; + ; + + +``` + +```mjs title=value.mjs +// ./value.js +/* export default */ const value = (42); + +export default value; + +``` \ No newline at end of file diff --git a/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/index.js b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/index.js new file mode 100644 index 000000000000..89ff3e2d977c --- /dev/null +++ b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/index.js @@ -0,0 +1 @@ +export const value = import("./value"); diff --git a/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/rspack.config.js b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/rspack.config.js new file mode 100644 index 000000000000..b24f4923fadb --- /dev/null +++ b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/rspack.config.js @@ -0,0 +1,9 @@ +const rspack = require('@rspack/core'); + +module.exports = { + target: 'web', + output: { + crossOriginLoading: 'anonymous', + }, + plugins: [new rspack.SubresourceIntegrityPlugin()], +}; diff --git a/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/test.config.js b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/test.config.js new file mode 100644 index 000000000000..ac2b6e38a8fc --- /dev/null +++ b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/test.config.js @@ -0,0 +1,19 @@ +const fs = require("fs"); +const path = require("path"); + +module.exports = { + findBundle: () => [], + validate(_stats, _stderr, options) { + const config = Array.isArray(options) ? options[0] : options; + const source = fs.readFileSync( + path.resolve(config.output.path, "runtime.mjs"), + "utf-8" + ); + const requireName = + config.experiments?.runtimeMode === "rspack" + ? "rspackRequire" + : "__webpack_require__"; + expect(source).toContain(`${requireName}.sriHashes`); + expect(source).not.toContain("__rspack_context.sriHashes"); + } +}; diff --git a/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/value.js b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/value.js new file mode 100644 index 000000000000..7a4e8a723a40 --- /dev/null +++ b/tests/rspack-test/esmOutputCases/runtime/modern-module-sri/value.js @@ -0,0 +1 @@ +export default 42;