Skip to content

Commit 8671bc1

Browse files
authored
fix: port public path of module chunk loading from webpack (#10425)
* fix: port webpack#19434 * fix: public path output module * fix: public path output module
1 parent 0cb5cc3 commit 8671bc1

File tree

23 files changed

+370
-32
lines changed

23 files changed

+370
-32
lines changed

crates/rspack_plugin_css/src/runtime/css_loading_with_hmr.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ var oldTags = [];
22
var newTags = [];
33
var applyHandler = function (options) {
44
return {
5-
dispose: function () {},
5+
dispose: function () { },
66
apply: function () {
77
var moduleIds = [];
88
newTags.forEach(function (info) {
@@ -15,8 +15,8 @@ var applyHandler = function (options) {
1515
while (newTags.length) {
1616
var info = newTags.pop();
1717
var chunkModuleIds = loadCssChunkData(__webpack_require__.m, info[0]);
18-
chunkModuleIds.forEach(function(id) {
19-
moduleIds.push(id)
18+
chunkModuleIds.forEach(function (id) {
19+
moduleIds.push(id)
2020
});
2121
}
2222
return moduleIds;
@@ -36,6 +36,7 @@ __webpack_require__.hmrC.css = function (
3636
applyHandlers,
3737
updatedModulesList
3838
) {
39+
if (typeof document === 'undefined') return;
3940
applyHandlers.push(applyHandler);
4041
chunkIds.forEach(function (chunkId) {
4142
var filename = __webpack_require__.k(chunkId);
@@ -70,11 +71,11 @@ __webpack_require__.hmrC.css = function (
7071
if (link.parentNode) link.parentNode.removeChild(link);
7172
return resolve();
7273
}
73-
} catch (e) {}
74+
} catch (e) { }
7475
var factories = {};
7576
loadCssChunkData(factories, link, chunkId);
76-
Object.keys(factories).forEach(function(id) {
77-
(updatedModulesList.push(id));
77+
Object.keys(factories).forEach(function (id) {
78+
(updatedModulesList.push(id));
7879
});
7980
link.sheet.disabled = true;
8081
oldTags.push(oldTag);

crates/rspack_plugin_css/src/runtime/css_loading_with_loading.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,11 @@ __webpack_require__.f.css = function (chunkId, promises, fetchPriority) {
4848
}
4949
}
5050
};
51-
var link = loadStylesheet(chunkId, url, loadingEnded, undefined, fetchPriority);
51+
if (typeof document !== 'undefined') {
52+
loadStylesheet(chunkId, url, loadingEnded, undefined, fetchPriority);
53+
} else {
54+
loadingEnded({ type: 'load' });
55+
}
5256
} else installedChunks[chunkId] = 0;
5357
}
5458
}

crates/rspack_plugin_css/src/runtime/mod.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ use rspack_core::{
66
basic_function, compile_boolean_matcher, impl_runtime_module, BooleanMatcher, ChunkGroupOrderKey,
77
ChunkUkey, Compilation, CrossOriginLoading, RuntimeGlobals, RuntimeModule, RuntimeModuleStage,
88
};
9-
use rspack_plugin_runtime::{chunk_has_css, get_chunk_runtime_requirements, stringify_chunks};
9+
use rspack_plugin_runtime::{
10+
chunk_has_css, get_chunk_runtime_requirements, is_neutral_platform, stringify_chunks,
11+
};
1012
use rustc_hash::FxHashSet as HashSet;
1113

1214
#[impl_runtime_module]
@@ -61,16 +63,17 @@ impl RuntimeModule for CssLoadingRuntimeModule {
6163
}
6264

6365
let environment = &compilation.options.output.environment;
66+
let is_neutral_platform = is_neutral_platform(compilation);
6467
let with_prefetch = runtime_requirements.contains(RuntimeGlobals::PREFETCH_CHUNK_HANDLERS)
65-
&& environment.supports_document()
68+
&& (environment.supports_document() || is_neutral_platform)
6669
&& chunk.has_child_by_order(
6770
compilation,
6871
&ChunkGroupOrderKey::Prefetch,
6972
true,
7073
&chunk_has_css,
7174
);
7275
let with_preload = runtime_requirements.contains(RuntimeGlobals::PRELOAD_CHUNK_HANDLERS)
73-
&& environment.supports_document()
76+
&& (environment.supports_document() || is_neutral_platform)
7477
&& chunk.has_child_by_order(
7578
compilation,
7679
&ChunkGroupOrderKey::Preload,

crates/rspack_plugin_runtime/src/helpers.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,3 +327,14 @@ pub fn get_chunk_runtime_requirements<'a>(
327327
) -> &'a RuntimeGlobals {
328328
ChunkGraph::get_chunk_runtime_requirements(compilation, chunk_ukey)
329329
}
330+
331+
pub fn is_neutral_platform(compilation: &Compilation) -> bool {
332+
// webpack uses `this.compilation.compiler.platform.node`
333+
!compilation.options.output.environment.supports_document()
334+
&& !compilation
335+
.options
336+
.resolve
337+
.condition_names
338+
.as_ref()
339+
.is_some_and(|c| c.contains(&"node".to_string()))
340+
}

crates/rspack_plugin_runtime/src/module_chunk_loading.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use rspack_core::{
22
ChunkLoading, ChunkLoadingType, ChunkUkey, Compilation, CompilationRuntimeRequirementInTree,
3-
Plugin, PluginContext, RuntimeGlobals, RuntimeModuleExt,
3+
Plugin, PluginContext, PublicPath, RuntimeGlobals, RuntimeModuleExt,
44
};
55
use rspack_error::Result;
66
use rspack_hook::{plugin, plugin_hook};
@@ -30,6 +30,11 @@ async fn runtime_requirements_in_tree(
3030
match runtime_requirement {
3131
RuntimeGlobals::ENSURE_CHUNK_HANDLERS if is_enabled_for_chunk => {
3232
has_chunk_loading = true;
33+
34+
if !matches!(compilation.options.output.public_path, PublicPath::Auto) {
35+
runtime_requirements_mut.insert(RuntimeGlobals::PUBLIC_PATH);
36+
}
37+
3338
runtime_requirements_mut.insert(RuntimeGlobals::GET_CHUNK_SCRIPT_FILENAME);
3439
}
3540
RuntimeGlobals::EXTERNAL_INSTALL_CHUNK if is_enabled_for_chunk => {
@@ -40,6 +45,11 @@ async fn runtime_requirements_in_tree(
4045
RuntimeGlobals::ON_CHUNKS_LOADED | RuntimeGlobals::BASE_URI if is_enabled_for_chunk => {
4146
has_chunk_loading = true;
4247
}
48+
RuntimeGlobals::PREFETCH_CHUNK_HANDLERS | RuntimeGlobals::PRELOAD_CHUNK_HANDLERS => {
49+
if is_enabled_for_chunk {
50+
runtime_requirements_mut.insert(RuntimeGlobals::PUBLIC_PATH);
51+
}
52+
}
4353
_ => {}
4454
}
4555
}

crates/rspack_plugin_runtime/src/runtime_module/module_chunk_loading.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ use cow_utils::CowUtils;
44
use rspack_collections::{DatabaseItem, Identifier};
55
use rspack_core::{
66
compile_boolean_matcher, impl_runtime_module, BooleanMatcher, Chunk, ChunkGroupOrderKey,
7-
ChunkUkey, Compilation, CrossOriginLoading, RuntimeGlobals, RuntimeModule, RuntimeModuleStage,
7+
ChunkUkey, Compilation, CrossOriginLoading, PublicPath, RuntimeGlobals, RuntimeModule,
8+
RuntimeModuleStage,
89
};
910

1011
use super::utils::{chunk_has_js, get_output_dir};
1112
use crate::{
12-
get_chunk_runtime_requirements,
13+
get_chunk_runtime_requirements, is_neutral_platform,
1314
runtime_module::utils::{get_initial_chunk_ids, stringify_chunks},
1415
LinkPrefetchData, LinkPreloadData, RuntimeModuleChunkWrapper, RuntimePlugin,
1516
};
@@ -103,22 +104,24 @@ impl RuntimeModule for ModuleChunkLoadingRuntimeModule {
103104

104105
let hooks = RuntimePlugin::get_compilation_hooks(compilation.id());
105106

107+
let is_neutral_platform = is_neutral_platform(compilation);
108+
106109
let with_base_uri = runtime_requirements.contains(RuntimeGlobals::BASE_URI);
107110
let with_external_install_chunk =
108111
runtime_requirements.contains(RuntimeGlobals::EXTERNAL_INSTALL_CHUNK);
109112
let with_loading = runtime_requirements.contains(RuntimeGlobals::ENSURE_CHUNK_HANDLERS);
110113
let with_on_chunk_load = runtime_requirements.contains(RuntimeGlobals::ON_CHUNKS_LOADED);
111114
let with_hmr = runtime_requirements.contains(RuntimeGlobals::HMR_DOWNLOAD_UPDATE_HANDLERS);
112115
let with_prefetch = runtime_requirements.contains(RuntimeGlobals::PREFETCH_CHUNK_HANDLERS)
113-
&& compilation.options.output.environment.supports_document()
116+
&& (compilation.options.output.environment.supports_document() || is_neutral_platform)
114117
&& chunk.has_child_by_order(
115118
compilation,
116119
&ChunkGroupOrderKey::Prefetch,
117120
true,
118121
&chunk_has_js,
119122
);
120123
let with_preload = runtime_requirements.contains(RuntimeGlobals::PRELOAD_CHUNK_HANDLERS)
121-
&& compilation.options.output.environment.supports_document()
124+
&& (compilation.options.output.environment.supports_document() || is_neutral_platform)
122125
&& chunk.has_child_by_order(
123126
compilation,
124127
&ChunkGroupOrderKey::Preload,
@@ -176,12 +179,17 @@ impl RuntimeModule for ModuleChunkLoadingRuntimeModule {
176179
let body = if matches!(has_js_matcher, BooleanMatcher::Condition(false)) {
177180
"installedChunks[chunkId] = 0;".to_string()
178181
} else {
182+
let output_dir = if matches!(compilation.options.output.public_path, PublicPath::Auto) {
183+
serde_json::to_string(&root_output_dir).expect("should able to serde_json::to_string")
184+
} else {
185+
RuntimeGlobals::PUBLIC_PATH.to_string()
186+
};
179187
compilation.runtime_template.render(
180188
&self.template(TemplateId::WithLoading),
181189
Some(serde_json::json!({
182190
"_js_matcher": &has_js_matcher.render("chunkId"),
183191
"_import_function_name":&compilation.options.output.import_function_name,
184-
"_output_dir": &root_output_dir,
192+
"_output_dir": &output_dir,
185193
"_match_fallback": if matches!(has_js_matcher, BooleanMatcher::Condition(true)) {
186194
""
187195
} else {
@@ -252,6 +260,7 @@ impl RuntimeModule for ModuleChunkLoadingRuntimeModule {
252260
Some(serde_json::json!({
253261
"_link_prefetch": &res.code,
254262
"_js_matcher": &js_matcher,
263+
"_is_neutral_platform": is_neutral_platform,
255264
})),
256265
)?;
257266

@@ -314,6 +323,7 @@ impl RuntimeModule for ModuleChunkLoadingRuntimeModule {
314323
Some(serde_json::json!({
315324
"_js_matcher": &js_matcher,
316325
"_link_preload": &res.code,
326+
"_is_neutral_platform": is_neutral_platform,
317327
})),
318328
)?;
319329

crates/rspack_plugin_runtime/src/runtime_module/runtime/module_chunk_loading_with_loading.ejs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ if (installedChunkData !== 0) { // 0 means "already installed".'
77
} else {
88
if (<%- _js_matcher %>) {
99
// setup Promise in chunk cache
10-
var promise = <%- _import_function_name %>("<%- _output_dir %>" + <%- GET_CHUNK_SCRIPT_FILENAME %>(chunkId)).then(installChunk, <%- basicFunction("e") %> {
10+
var promise = <%- _import_function_name %>(<%- _output_dir %> + <%- GET_CHUNK_SCRIPT_FILENAME %>(chunkId)).then(installChunk, <%- basicFunction("e") %> {
1111
if (installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;
1212
throw e;
1313
});

crates/rspack_plugin_runtime/src/runtime_module/runtime/module_chunk_loading_with_prefetch.ejs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<%- PREFETCH_CHUNK_HANDLERS %>.j = <%- basicFunction("chunkId") %> {
2-
if (typeof document === 'undefined') return;
2+
<% if _is_neutral_platform { %>if (typeof document === 'undefined') return;<% } %>
33
if((!<%- HAS_OWN_PROPERTY %>(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && <%- _js_matcher %>) {
44
installedChunks[chunkId] = null;
55
<%- _link_prefetch %>

crates/rspack_plugin_runtime/src/runtime_module/runtime/module_chunk_loading_with_preload.ejs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<%- PRELOAD_CHUNK_HANDLERS %>.j = <%- basicFunction("chunkId") %> {
2-
if (typeof document === 'undefined') return;
2+
<% if _is_neutral_platform { %>if (typeof document === 'undefined') return;<% } %>
33
if((!<%- HAS_OWN_PROPERTY %>(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && <%- _js_matcher %>) {
44
installedChunks[chunkId] = null;
55
<%- _link_preload %>

packages/rspack-test-tools/tests/configCases/library/modern-module-force-concaten/__snapshot__/h.js.txt

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,28 @@ return module.exports;
2222
}
2323

2424
/************************************************************************/
25-
// webpack/runtime/public_path
25+
// webpack/runtime/global
2626
(() => {
27-
__webpack_require__.p = "";
27+
__webpack_require__.g = (() => {
28+
if (typeof globalThis === 'object') return globalThis;
29+
try {
30+
return this || new Function('return this')();
31+
} catch (e) {
32+
if (typeof window === 'object') return window;
33+
}
34+
})();
35+
})();
36+
// webpack/runtime/auto_public_path
37+
(() => {
38+
var scriptUrl;
39+
40+
if (typeof import.meta.url === "string") scriptUrl = import.meta.url
41+
42+
// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration",
43+
// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.',
44+
if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
45+
scriptUrl = scriptUrl.replace(/^blob:/, "").replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
46+
__webpack_require__.p = scriptUrl
2847
})();
2948
/************************************************************************/
3049

0 commit comments

Comments
 (0)