Skip to content

Commit 0ca7752

Browse files
authored
refactor: render __webpack_require__ in static code by runtime template (#12284)
* refactor: render __webpack_require__ by runtime template in dead code * refactor: render __webpack_require__ by runtime template in dead code
1 parent d388225 commit 0ca7752

File tree

23 files changed

+228
-87
lines changed

23 files changed

+228
-87
lines changed

crates/rspack_plugin_esm_library/src/render.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ impl EsmLibraryPlugin {
204204
// __webpack_require__.add({ "./src/main.js"(require, exports) { ... } })
205205
decl_source.add(RawStringSource::from(format!(
206206
"{}({{\n",
207-
RegisterModuleRuntime::runtime_id()
207+
RegisterModuleRuntime::runtime_id(&compilation.runtime_template)
208208
)));
209209
decl_source.add(decl_inner);
210210
decl_source.add(RawStringSource::from_static("});\n"));

crates/rspack_plugin_esm_library/src/runtime.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
use rspack_core::{
2-
Compilation, ModuleIdentifier, RuntimeGlobals, RuntimeModule, impl_runtime_module,
2+
Compilation, ModuleIdentifier, RuntimeGlobals, RuntimeModule, RuntimeTemplate,
3+
impl_runtime_module,
34
};
45

56
#[impl_runtime_module]
67
#[derive(Default, Debug)]
78
pub(crate) struct RegisterModuleRuntime {}
89

910
impl RegisterModuleRuntime {
10-
pub(crate) fn runtime_id() -> &'static str {
11-
"__webpack_require__.add"
11+
pub(crate) fn runtime_id(runtime_template: &RuntimeTemplate) -> String {
12+
format!(
13+
"{}.add",
14+
runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE)
15+
)
1216
}
1317
}
1418

@@ -21,7 +25,7 @@ impl RuntimeModule for RegisterModuleRuntime {
2125
async fn generate(&self, compilation: &Compilation) -> rspack_error::Result<String> {
2226
Ok(format!(
2327
"{} = function registerModules(modules) {{ Object.assign({}, modules) }}\n",
24-
Self::runtime_id(),
28+
Self::runtime_id(&compilation.runtime_template),
2529
compilation
2630
.runtime_template
2731
.render_runtime_globals(&RuntimeGlobals::MODULE_FACTORIES),

crates/rspack_plugin_extract_css/src/plugin.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -538,7 +538,12 @@ async fn runtime_requirement_in_tree(
538538
"css",
539539
"mini-css",
540540
SOURCE_TYPE[0],
541-
"__webpack_require__.miniCssF".into(),
541+
format!(
542+
"{}.miniCssF",
543+
compilation
544+
.runtime_template
545+
.render_runtime_globals(&RuntimeGlobals::REQUIRE)
546+
),
542547
move |runtime_requirements| {
543548
runtime_requirements.contains(RuntimeGlobals::HMR_DOWNLOAD_UPDATE_HANDLERS)
544549
},

crates/rspack_plugin_javascript/src/parser_plugin/define_plugin/utils.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{borrow::Cow, sync::LazyLock};
1+
use std::borrow::Cow;
22

33
use itertools::Itertools as _;
44
use regex::Regex;
@@ -7,11 +7,6 @@ use serde_json::{Value, json};
77

88
use crate::visitors::{DestructuringAssignmentProperties, JavascriptParser};
99

10-
static REQUIRE_FUNCTION_REGEX: LazyLock<Regex> = LazyLock::new(|| {
11-
Regex::new("__webpack_require__\\s*(!?\\.)").expect("should init `REQUIRE_FUNCTION_REGEX`")
12-
});
13-
static REQUIRE_IDENTIFIER: &str = "__webpack_require__";
14-
1510
pub fn gen_const_dep(
1611
parser: &JavascriptParser,
1712
code: Cow<str>,
@@ -33,9 +28,14 @@ pub fn gen_const_dep(
3328
)
3429
};
3530

36-
if REQUIRE_FUNCTION_REGEX.is_match(&code) {
31+
let require_name = parser
32+
.runtime_template
33+
.render_runtime_globals(&RuntimeGlobals::REQUIRE);
34+
let require_function_regex = Regex::new(&format!("{}\\s*(!?\\.)", &require_name))
35+
.expect("should init `REQUIRE_FUNCTION_REGEX`");
36+
if require_function_regex.is_match(&code) {
3737
to_const_dep(Some(RuntimeGlobals::REQUIRE))
38-
} else if code.contains(REQUIRE_IDENTIFIER) {
38+
} else if code.contains(&require_name) {
3939
to_const_dep(Some(RuntimeGlobals::REQUIRE_SCOPE))
4040
} else {
4141
to_const_dep(None)

crates/rspack_plugin_javascript/src/plugin/mod.rs

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -183,20 +183,35 @@ impl JsPlugin {
183183
let module_execution = if runtime_requirements
184184
.contains(RuntimeGlobals::INTERCEPT_MODULE_EXECUTION)
185185
{
186-
indoc!{r#"
187-
var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };
188-
__webpack_require__.i.forEach(function(handler) { handler(execOptions); });
186+
format!(r#"
187+
var execOptions = {{ id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: {} }};
188+
{}.forEach(function(handler) {{ handler(execOptions); }});
189189
module = execOptions.module;
190-
if (!execOptions.factory) {
190+
if (!execOptions.factory) {{
191191
console.error("undefined factory", moduleId);
192192
throw Error("RuntimeError: factory is undefined (" + moduleId + ")");
193-
}
193+
}}
194194
execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
195-
"#}.into()
195+
"#,
196+
compilation.runtime_template.render_runtime_globals(&RuntimeGlobals::REQUIRE),
197+
compilation.runtime_template.render_runtime_globals(&RuntimeGlobals::INTERCEPT_MODULE_EXECUTION)
198+
).into()
196199
} else if runtime_requirements.contains(RuntimeGlobals::THIS_AS_EXPORTS) {
197-
"__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n".into()
200+
format!(
201+
"__webpack_modules__[moduleId].call(module.exports, module, module.exports, {});\n",
202+
compilation
203+
.runtime_template
204+
.render_runtime_globals(&RuntimeGlobals::REQUIRE)
205+
)
206+
.into()
198207
} else {
199-
"__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n".into()
208+
format!(
209+
"__webpack_modules__[moduleId](module, module.exports, {});\n",
210+
compilation
211+
.runtime_template
212+
.render_runtime_globals(&RuntimeGlobals::REQUIRE)
213+
)
214+
.into()
200215
};
201216

202217
if strict_module_error_handling {

crates/rspack_plugin_javascript/src/visitors/dependency/parser/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ pub struct JavascriptParser<'parser> {
325325
pub resource_data: &'parser ResourceData,
326326
pub(crate) compiler_options: &'parser CompilerOptions,
327327
pub(crate) javascript_options: &'parser JavascriptParserOptions,
328-
pub(crate) runtime_template: &'parser RuntimeTemplate,
328+
pub runtime_template: &'parser RuntimeTemplate,
329329
pub module_type: &'parser ModuleType,
330330
pub(crate) module_layer: Option<&'parser ModuleLayer>,
331331
pub module_identifier: &'parser ModuleIdentifier,

crates/rspack_plugin_lazy_compilation/src/module.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,10 @@ impl Module for LazyCompilationProxyModule {
221221
let block = self.blocks.first();
222222

223223
let client = format!(
224-
"var client = __webpack_require__(\"{}\");\nvar data = {};",
224+
"var client = {}(\"{}\");\nvar data = {};",
225+
compilation
226+
.runtime_template
227+
.render_runtime_globals(&RuntimeGlobals::REQUIRE),
225228
ChunkGraph::get_module_id(&compilation.module_ids_artifact, *client_module)
226229
.expect("should have module id"),
227230
serde_json::to_string(&self.identifier).expect("should serialize identifier")

crates/rspack_plugin_mf/src/container/container_entry_module.rs

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -211,12 +211,24 @@ impl Module for ContainerEntryModule {
211211
compilation
212212
.runtime_template
213213
.render_runtime_globals(&RuntimeGlobals::DEFINE_PROPERTY_GETTERS),
214-
compilation
215-
.runtime_template
216-
.returning_function("__webpack_require__.getContainer", ""),
217-
compilation
218-
.runtime_template
219-
.returning_function("__webpack_require__.initContainer", ""),
214+
compilation.runtime_template.returning_function(
215+
&format!(
216+
"{}.getContainer",
217+
compilation
218+
.runtime_template
219+
.render_runtime_globals(&RuntimeGlobals::REQUIRE)
220+
),
221+
""
222+
),
223+
compilation.runtime_template.returning_function(
224+
&format!(
225+
"{}.initContainer",
226+
compilation
227+
.runtime_template
228+
.render_runtime_globals(&RuntimeGlobals::REQUIRE)
229+
),
230+
""
231+
),
220232
)
221233
} else {
222234
format!(

crates/rspack_plugin_mf/src/container/expose_runtime_module.rs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use rspack_collections::Identifier;
22
use rspack_core::{
3-
ChunkUkey, Compilation, RuntimeModule, RuntimeModuleStage, SourceType, impl_runtime_module,
3+
ChunkUkey, Compilation, RuntimeGlobals, RuntimeModule, RuntimeModuleStage, SourceType,
4+
impl_runtime_module,
45
};
56

67
use super::container_entry_module::CodeGenerationDataExpose;
@@ -64,18 +65,27 @@ impl RuntimeModule for ExposeRuntimeModule {
6465
return Ok("".to_string());
6566
};
6667
let module_map = data.module_map.render(compilation);
68+
let require_name = compilation
69+
.runtime_template
70+
.render_runtime_globals(&RuntimeGlobals::REQUIRE);
6771
let mut source = format!(
6872
r#"
69-
__webpack_require__.initializeExposesData = {{
73+
{require_name}.initializeExposesData = {{
7074
moduleMap: {},
7175
shareScope: {},
7276
}};
7377
"#,
7478
module_map,
7579
json_stringify(&data.share_scope)
7680
);
77-
source += "__webpack_require__.getContainer = __webpack_require__.getContainer || function() { throw new Error(\"should have __webpack_require__.getContainer\") };";
78-
source += "__webpack_require__.initContainer = __webpack_require__.initContainer || function() { throw new Error(\"should have __webpack_require__.initContainer\") };";
81+
source += &format!(
82+
"{require_name}.getContainer = {require_name}.getContainer || function() {{ throw new Error(\"should have {require_name}.getContainer\") }};",
83+
require_name = require_name,
84+
);
85+
source += &format!(
86+
"{require_name}.initContainer = {require_name}.initContainer || function() {{ throw new Error(\"should have {require_name}.initContainer\") }};",
87+
require_name = require_name,
88+
);
7989
Ok(source)
8090
}
8191

crates/rspack_plugin_mf/src/container/remote_runtime_module.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use rspack_collections::{Identifiable, Identifier};
22
use rspack_core::{
3-
ChunkGraph, ChunkUkey, Compilation, DependenciesBlock, ModuleId, RuntimeModule,
3+
ChunkGraph, ChunkUkey, Compilation, DependenciesBlock, ModuleId, RuntimeGlobals, RuntimeModule,
44
RuntimeModuleStage, SourceType, impl_runtime_module,
55
};
66
use rustc_hash::FxHashMap;
@@ -91,16 +91,25 @@ impl RuntimeModule for RemoteRuntimeModule {
9191
remotes,
9292
);
9393
}
94+
9495
let remotes_loading_impl = if self.enhanced {
95-
"__webpack_require__.f.remotes = __webpack_require__.f.remotes || function() { throw new Error(\"should have __webpack_require__.f.remotes\"); }"
96+
format!(
97+
"{ensure_chunk_handlers}.remotes = {ensure_chunk_handlers}.remotes || function() {{ throw new Error(\"should have {ensure_chunk_handlers}.remotes\"); }}",
98+
ensure_chunk_handlers = compilation
99+
.runtime_template
100+
.render_runtime_globals(&RuntimeGlobals::ENSURE_CHUNK_HANDLERS),
101+
)
96102
} else {
97-
include_str!("./remotesLoading.js")
103+
include_str!("./remotesLoading.js").to_string()
98104
};
99105
Ok(format!(
100106
r#"
101-
__webpack_require__.remotesLoadingData = {{ chunkMapping: {chunk_mapping}, moduleIdToRemoteDataMapping: {id_to_remote_data_mapping} }};
107+
{require_name}.remotesLoadingData = {{ chunkMapping: {chunk_mapping}, moduleIdToRemoteDataMapping: {id_to_remote_data_mapping} }};
102108
{remotes_loading_impl}
103109
"#,
110+
require_name = compilation
111+
.runtime_template
112+
.render_runtime_globals(&RuntimeGlobals::REQUIRE),
104113
chunk_mapping = json_stringify(&chunk_to_remotes_mapping),
105114
id_to_remote_data_mapping = json_stringify(&id_to_remote_data_mapping),
106115
remotes_loading_impl = remotes_loading_impl,

0 commit comments

Comments
 (0)