Skip to content

Commit 6951bea

Browse files
feat: render jsonp_chunk_loading template with dojang (#9496)
1 parent a3b9472 commit 6951bea

File tree

15 files changed

+195
-146
lines changed

15 files changed

+195
-146
lines changed

crates/rspack_plugin_runtime/src/runtime_module/jsonp_chunk_loading.rs

Lines changed: 116 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,71 @@ impl JsonpChunkLoadingRuntimeModule {
4242
.unwrap_or_else(|| "document.baseURI || self.location.href".to_string());
4343
RawStringSource::from(format!("{} = {};\n", RuntimeGlobals::BASE_URI, base_uri)).boxed()
4444
}
45+
46+
fn template_id(&self, id: TemplateId) -> String {
47+
let base_id = self.id.as_str();
48+
49+
match id {
50+
TemplateId::Raw => base_id.to_string(),
51+
TemplateId::WithPrefetch => format!("{}_with_prefetch", base_id),
52+
TemplateId::WithPreload => format!("{}_with_preload", base_id),
53+
TemplateId::WithHmr => format!("{}_with_hmr", base_id),
54+
TemplateId::WithHmrManifest => format!("{}_with_hmr_manifest", base_id),
55+
TemplateId::WithOnChunkLoad => format!("{}_with_on_chunk_load", base_id),
56+
TemplateId::WithCallback => format!("{}_with_callback", base_id),
57+
}
58+
}
59+
}
60+
61+
#[allow(clippy::enum_variant_names)]
62+
enum TemplateId {
63+
Raw,
64+
WithPrefetch,
65+
WithPreload,
66+
WithHmr,
67+
WithHmrManifest,
68+
WithOnChunkLoad,
69+
WithCallback,
4570
}
4671

4772
impl RuntimeModule for JsonpChunkLoadingRuntimeModule {
4873
fn name(&self) -> Identifier {
4974
self.id
5075
}
5176

77+
fn template(&self) -> Vec<(String, String)> {
78+
vec![
79+
(
80+
self.template_id(TemplateId::Raw),
81+
include_str!("runtime/jsonp_chunk_loading.ejs").to_string(),
82+
),
83+
(
84+
self.template_id(TemplateId::WithPrefetch),
85+
include_str!("runtime/jsonp_chunk_loading_with_prefetch.ejs").to_string(),
86+
),
87+
(
88+
self.template_id(TemplateId::WithPreload),
89+
include_str!("runtime/jsonp_chunk_loading_with_preload.ejs").to_string(),
90+
),
91+
(
92+
self.template_id(TemplateId::WithHmr),
93+
include_str!("runtime/jsonp_chunk_loading_with_hmr.ejs").to_string(),
94+
),
95+
(
96+
self.template_id(TemplateId::WithHmrManifest),
97+
include_str!("runtime/jsonp_chunk_loading_with_hmr_manifest.ejs").to_string(),
98+
),
99+
(
100+
self.template_id(TemplateId::WithOnChunkLoad),
101+
include_str!("runtime/jsonp_chunk_loading_with_on_chunk_load.ejs").to_string(),
102+
),
103+
(
104+
self.template_id(TemplateId::WithCallback),
105+
include_str!("runtime/jsonp_chunk_loading_with_callback.ejs").to_string(),
106+
),
107+
]
108+
}
109+
52110
fn generate(&self, compilation: &Compilation) -> rspack_error::Result<BoxSource> {
53111
let chunk = compilation
54112
.chunk_by_ukey
@@ -106,25 +164,22 @@ impl RuntimeModule for JsonpChunkLoadingRuntimeModule {
106164
let body = if matches!(has_js_matcher, BooleanMatcher::Condition(false)) {
107165
"installedChunks[chunkId] = 0;".to_string()
108166
} else {
109-
include_str!("runtime/jsonp_chunk_loading.js")
110-
.cow_replace("$JS_MATCHER$", &js_matcher)
111-
.cow_replace(
112-
"$MATCH_FALLBACK$",
113-
if matches!(has_js_matcher, BooleanMatcher::Condition(true)) {
167+
compilation.runtime_template.render(
168+
&self.template_id(TemplateId::Raw),
169+
Some(serde_json::json!({
170+
"_js_matcher": &js_matcher,
171+
"_match_fallback": if matches!(has_js_matcher, BooleanMatcher::Condition(true)) {
114172
""
115173
} else {
116174
"else installedChunks[chunkId] = 0;\n"
117175
},
118-
)
119-
.cow_replace(
120-
"$FETCH_PRIORITY$",
121-
if with_fetch_priority {
122-
", fetchPriority"
176+
"_fetch_priority": if with_fetch_priority {
177+
", fetchPriority"
123178
} else {
124-
""
179+
""
125180
},
126-
)
127-
.into_owned()
181+
})),
182+
)?
128183
};
129184

130185
source.add(RawStringSource::from(format!(
@@ -186,12 +241,15 @@ impl RuntimeModule for JsonpChunkLoadingRuntimeModule {
186241
.await
187242
})?;
188243

189-
source.add(RawStringSource::from(
190-
include_str!("runtime/jsonp_chunk_loading_with_prefetch.js")
191-
.cow_replace("$JS_MATCHER$", &js_matcher)
192-
.cow_replace("$LINK_PREFETCH$", &res.code)
193-
.into_owned(),
194-
));
244+
let source_with_prefetch = compilation.runtime_template.render(
245+
&self.template_id(TemplateId::WithPrefetch),
246+
Some(serde_json::json!({
247+
"_js_matcher": &js_matcher,
248+
"_link_prefetch": &res.code,
249+
})),
250+
)?;
251+
252+
source.add(RawStringSource::from(source_with_prefetch));
195253
}
196254

197255
if with_preload && !matches!(has_js_matcher, BooleanMatcher::Condition(false)) {
@@ -268,59 +326,64 @@ impl RuntimeModule for JsonpChunkLoadingRuntimeModule {
268326
.await
269327
})?;
270328

271-
source.add(RawStringSource::from(
272-
include_str!("runtime/jsonp_chunk_loading_with_preload.js")
273-
.cow_replace("$JS_MATCHER$", &js_matcher)
274-
.cow_replace("$LINK_PRELOAD$", &res.code)
275-
.into_owned(),
276-
));
329+
let source_with_preload = compilation.runtime_template.render(
330+
&self.template_id(TemplateId::WithPreload),
331+
Some(serde_json::json!({
332+
"_js_matcher": &js_matcher,
333+
"_link_preload": &res.code,
334+
})),
335+
)?;
336+
337+
source.add(RawStringSource::from(source_with_preload));
277338
}
278339

279340
if with_hmr {
280-
source.add(RawStringSource::from(
281-
include_str!("runtime/jsonp_chunk_loading_with_hmr.js")
282-
.cow_replace("$GLOBAL_OBJECT$", &compilation.options.output.global_object)
283-
.cow_replace(
284-
"$HOT_UPDATE_GLOBAL$",
285-
&serde_json::to_string(&compilation.options.output.hot_update_global)
286-
.expect("failed to serde_json::to_string(hot_update_global)"),
287-
)
288-
.into_owned(),
289-
));
341+
let source_with_hmr = compilation
342+
.runtime_template
343+
.render(&self.template_id(TemplateId::WithHmr), Some(serde_json::json!({
344+
"_global_object": &compilation.options.output.global_object,
345+
"_hot_update_global": &serde_json::to_string(&compilation.options.output.hot_update_global).expect("failed to serde_json::to_string(hot_update_global)"),
346+
})))?;
347+
348+
source.add(RawStringSource::from(source_with_hmr));
290349
source.add(RawStringSource::from(generate_javascript_hmr_runtime(
291350
"jsonp",
292351
)));
293352
}
294353

295354
if with_hmr_manifest {
296-
source.add(RawStringSource::from_static(include_str!(
297-
"runtime/jsonp_chunk_loading_with_hmr_manifest.js"
298-
)));
355+
let source_with_hmr_manifest = compilation
356+
.runtime_template
357+
.render(&self.template_id(TemplateId::WithHmrManifest), None)?;
358+
359+
source.add(RawStringSource::from(source_with_hmr_manifest));
299360
}
300361

301362
if with_on_chunk_load {
302-
source.add(RawStringSource::from_static(include_str!(
303-
"runtime/jsonp_chunk_loading_with_on_chunk_load.js"
304-
)));
363+
let source_with_on_chunk_load = compilation
364+
.runtime_template
365+
.render(&self.template_id(TemplateId::WithOnChunkLoad), None)?;
366+
367+
source.add(RawStringSource::from(source_with_on_chunk_load));
305368
}
306369

307370
if with_callback || with_loading {
308371
let chunk_loading_global_expr = format!(
309372
r#"{}["{}"]"#,
310373
&compilation.options.output.global_object, &compilation.options.output.chunk_loading_global
311374
);
312-
source.add(RawStringSource::from(
313-
include_str!("runtime/jsonp_chunk_loading_with_callback.js")
314-
.cow_replace("$CHUNK_LOADING_GLOBAL_EXPR$", &chunk_loading_global_expr)
315-
.cow_replace(
316-
"$WITH_ON_CHUNK_LOAD$",
317-
match with_on_chunk_load {
318-
true => "return __webpack_require__.O(result);",
319-
false => "",
320-
},
321-
)
322-
.into_owned(),
323-
));
375+
let source_with_callback = compilation.runtime_template.render(
376+
&self.template_id(TemplateId::WithCallback),
377+
Some(serde_json::json!({
378+
"_chunk_loading_global_expr": &chunk_loading_global_expr,
379+
"_with_on_chunk_load": match with_on_chunk_load {
380+
true => format!("return {}(result);", RuntimeGlobals::ON_CHUNKS_LOADED.name()),
381+
false => "".to_string(),
382+
},
383+
})),
384+
)?;
385+
386+
source.add(RawStringSource::from(source_with_callback));
324387
}
325388

326389
Ok(source.boxed())

crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading.js renamed to crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading.ejs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// JSONP chunk loading for javascript
2-
var installedChunkData = __webpack_require__.o(installedChunks, chunkId)
2+
var installedChunkData = <%- HAS_OWN_PROPERTY %>(installedChunks, chunkId)
33
? installedChunks[chunkId]
44
: undefined;
55
if (installedChunkData !== 0) {
@@ -9,19 +9,17 @@ if (installedChunkData !== 0) {
99
if (installedChunkData) {
1010
promises.push(installedChunkData[2]);
1111
} else {
12-
if ($JS_MATCHER$) {
12+
if (<%- _js_matcher %>) {
1313
// setup Promise in chunk cache
14-
var promise = new Promise(function (resolve, reject) {
15-
installedChunkData = installedChunks[chunkId] = [resolve, reject];
16-
});
14+
var promise = new Promise(<%- expressionFunction("installedChunkData = installedChunks[chunkId] = [resolve, reject]", "resolve, reject") %>);
1715
promises.push((installedChunkData[2] = promise));
1816

1917
// start chunk loading
20-
var url = __webpack_require__.p + __webpack_require__.u(chunkId);
18+
var url = <%- PUBLIC_PATH %> + <%- GET_CHUNK_SCRIPT_FILENAME %>(chunkId);
2119
// create error before stack unwound to get useful stacktrace later
2220
var error = new Error();
2321
var loadingEnded = function (event) {
24-
if (__webpack_require__.o(installedChunks, chunkId)) {
22+
if (<%- HAS_OWN_PROPERTY %>(installedChunks, chunkId)) {
2523
installedChunkData = installedChunks[chunkId];
2624
if (installedChunkData !== 0) installedChunks[chunkId] = undefined;
2725
if (installedChunkData) {
@@ -43,7 +41,7 @@ if (installedChunkData !== 0) {
4341
}
4442
}
4543
};
46-
__webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId$FETCH_PRIORITY$);
47-
} $MATCH_FALLBACK$
44+
__webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId<%- _fetch_priority %>);
45+
} <%- _match_fallback %>
4846
}
4947
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// install a JSONP callback for chunk loading
2+
var webpackJsonpCallback = <%- basicFunction("parentChunkLoadingFunction, data") %> {
3+
<%- destructureArray("chunkIds, moreModules, runtime", "data") %>
4+
// add "moreModules" to the modules object,
5+
// then flag all "chunkIds" as loaded and fire callback
6+
var moduleId, chunkId, i = 0;
7+
if (chunkIds.some(<%- returningFunction("installedChunks[id] !== 0", "id") %>)) {
8+
for (moduleId in moreModules) {
9+
if (<%- HAS_OWN_PROPERTY %>(moreModules, moduleId)) {
10+
<%- MODULE_FACTORIES %>[moduleId] = moreModules[moduleId];
11+
}
12+
}
13+
if (runtime) var result = runtime(<%- REQUIRE %>);
14+
}
15+
if (parentChunkLoadingFunction) parentChunkLoadingFunction(data);
16+
for (; i < chunkIds.length; i++) {
17+
chunkId = chunkIds[i];
18+
if (
19+
<%- HAS_OWN_PROPERTY %>(installedChunks, chunkId) &&
20+
installedChunks[chunkId]
21+
) {
22+
installedChunks[chunkId][0]();
23+
}
24+
installedChunks[chunkId] = 0;
25+
}
26+
<%- _with_on_chunk_load %>
27+
};
28+
29+
var chunkLoadingGlobal = <%- _chunk_loading_global_expr %> = <%- _chunk_loading_global_expr %> || [];
30+
chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
31+
chunkLoadingGlobal.push = webpackJsonpCallback.bind(
32+
null,
33+
chunkLoadingGlobal.push.bind(chunkLoadingGlobal)
34+
);

crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading_with_callback.js

Lines changed: 0 additions & 38 deletions
This file was deleted.

crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading_with_hmr.js renamed to crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading_with_hmr.ejs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ var currentUpdatedModulesList;
22
var waitingUpdateResolves = {};
33
function loadUpdateChunk(chunkId, updatedModulesList) {
44
currentUpdatedModulesList = updatedModulesList;
5-
return new Promise(function (resolve, reject) {
5+
return new Promise(<%- basicFunction("resolve, reject") %> {
66
waitingUpdateResolves[chunkId] = resolve;
77
// start update chunk loading
8-
var url = __webpack_require__.p + __webpack_require__.hu(chunkId);
8+
var url = <%- PUBLIC_PATH %> + <%- GET_CHUNK_UPDATE_SCRIPT_FILENAME %>(chunkId);
99
// create error before stack unwound to get useful stacktrace later
1010
var error = new Error();
11-
var loadingEnded = function (event) {
11+
var loadingEnded = <%- basicFunction("event") %> {
1212
if (waitingUpdateResolves[chunkId]) {
1313
waitingUpdateResolves[chunkId] = undefined;
1414
var errorType =
@@ -28,13 +28,13 @@ function loadUpdateChunk(chunkId, updatedModulesList) {
2828
reject(error);
2929
}
3030
};
31-
__webpack_require__.l(url, loadingEnded);
31+
<%- LOAD_SCRIPT %>(url, loadingEnded);
3232
});
3333
}
3434

35-
$GLOBAL_OBJECT$[$HOT_UPDATE_GLOBAL$] = function (chunkId, moreModules, runtime) {
35+
<%- _global_object %>[<%- _hot_update_global %>] = <%- basicFunction("chunkId, moreModules, runtime") %> {
3636
for (var moduleId in moreModules) {
37-
if (__webpack_require__.o(moreModules, moduleId)) {
37+
if (<%- HAS_OWN_PROPERTY %>(moreModules, moduleId)) {
3838
currentUpdate[moduleId] = moreModules[moduleId];
3939
if (currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);
4040
}

crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading_with_hmr_manifest.js renamed to crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading_with_hmr_manifest.ejs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
__webpack_require__.hmrM = function () {
1+
<%- HMR_DOWNLOAD_MANIFEST %> = <%- basicFunction("") %> {
22
if (typeof fetch === "undefined")
33
throw new Error("No browser support: need fetch API");
4-
return fetch(__webpack_require__.p + __webpack_require__.hmrF()).then(
5-
function (response) {
4+
return fetch(<%- PUBLIC_PATH %> + <%- GET_UPDATE_MANIFEST_FILENAME %>()).then(
5+
<%- basicFunction("response") %> {
66
if (response.status === 404) return; // no update available
77
if (!response.ok)
88
throw new Error(
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<%- ON_CHUNKS_LOADED %>.j = <%- returningFunction("installedChunks[chunkId] === 0", "chunkId") %>;

crates/rspack_plugin_runtime/src/runtime_module/runtime/jsonp_chunk_loading_with_on_chunk_load.js

Lines changed: 0 additions & 3 deletions
This file was deleted.

0 commit comments

Comments
 (0)