Skip to content

Commit cd22df7

Browse files
authored
refactor: render javascript runtime globals according to compiler options (#12371)
* refactor: render javascript runtime globals according to compiler options * refactor: render javascript runtime globals according to compiler options * refactor: render javascript runtime globals according to compiler options * refactor: remove unnecessary template string in RuntimeGlobals * feat: add missing RuntimeGlobals from Rust implementation - Add startupChunkDependencies - Add rspackVersion (internal) - Add rspackUniqueId (internal) These RuntimeGlobals exist in Rust but were missing in TypeScript. * chore: update API documentation for RuntimeGlobals * refactor: render javascript runtime globals according to compiler options
1 parent fad967a commit cd22df7

File tree

18 files changed

+611
-377
lines changed

18 files changed

+611
-377
lines changed

crates/rspack_binding_api/src/runtime.rs

Lines changed: 3 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -21,88 +21,11 @@ static RUNTIME_GLOBAL_MAP: LazyLock<RuntimeGlobalMap> = LazyLock::new(|| {
2121
let mut to_js_map = FxHashMap::default();
2222
let mut from_js_map = FxHashMap::default();
2323

24-
macro_rules! declare_runtime_global {
25-
($name:ident) => {
26-
to_js_map.insert(
27-
RuntimeGlobals::$name,
28-
stringify!($name).to_lower_camel_case().into(),
29-
);
30-
from_js_map.insert(stringify!($name), RuntimeGlobals::$name);
31-
};
24+
for (name, value) in RuntimeGlobals::all().iter_names() {
25+
to_js_map.insert(value, name.to_lower_camel_case());
26+
from_js_map.insert(name, value);
3227
}
3328

34-
declare_runtime_global!(REQUIRE_SCOPE);
35-
declare_runtime_global!(MODULE);
36-
declare_runtime_global!(MODULE_ID);
37-
declare_runtime_global!(REQUIRE);
38-
declare_runtime_global!(MODULE_CACHE);
39-
declare_runtime_global!(ENSURE_CHUNK);
40-
declare_runtime_global!(ENSURE_CHUNK_HANDLERS);
41-
declare_runtime_global!(PUBLIC_PATH);
42-
declare_runtime_global!(GET_CHUNK_SCRIPT_FILENAME);
43-
declare_runtime_global!(GET_CHUNK_CSS_FILENAME);
44-
declare_runtime_global!(LOAD_SCRIPT);
45-
declare_runtime_global!(HAS_OWN_PROPERTY);
46-
declare_runtime_global!(MODULE_FACTORIES_ADD_ONLY);
47-
declare_runtime_global!(ON_CHUNKS_LOADED);
48-
declare_runtime_global!(CHUNK_CALLBACK);
49-
declare_runtime_global!(MODULE_FACTORIES);
50-
declare_runtime_global!(INTERCEPT_MODULE_EXECUTION);
51-
declare_runtime_global!(HMR_DOWNLOAD_MANIFEST);
52-
declare_runtime_global!(HMR_DOWNLOAD_UPDATE_HANDLERS);
53-
declare_runtime_global!(GET_UPDATE_MANIFEST_FILENAME);
54-
declare_runtime_global!(GET_CHUNK_UPDATE_SCRIPT_FILENAME);
55-
declare_runtime_global!(GET_CHUNK_UPDATE_CSS_FILENAME);
56-
declare_runtime_global!(HMR_MODULE_DATA);
57-
declare_runtime_global!(HMR_RUNTIME_STATE_PREFIX);
58-
declare_runtime_global!(EXTERNAL_INSTALL_CHUNK);
59-
declare_runtime_global!(GET_FULL_HASH);
60-
declare_runtime_global!(GLOBAL);
61-
declare_runtime_global!(RETURN_EXPORTS_FROM_RUNTIME);
62-
declare_runtime_global!(INSTANTIATE_WASM);
63-
declare_runtime_global!(ASYNC_MODULE);
64-
declare_runtime_global!(BASE_URI);
65-
declare_runtime_global!(MODULE_LOADED);
66-
declare_runtime_global!(STARTUP_ENTRYPOINT);
67-
declare_runtime_global!(STARTUP_CHUNK_DEPENDENCIES);
68-
declare_runtime_global!(CREATE_SCRIPT_URL);
69-
declare_runtime_global!(CREATE_SCRIPT);
70-
declare_runtime_global!(GET_TRUSTED_TYPES_POLICY);
71-
declare_runtime_global!(DEFINE_PROPERTY_GETTERS);
72-
declare_runtime_global!(ENTRY_MODULE_ID);
73-
declare_runtime_global!(STARTUP_NO_DEFAULT);
74-
declare_runtime_global!(ENSURE_CHUNK_INCLUDE_ENTRIES);
75-
declare_runtime_global!(STARTUP);
76-
declare_runtime_global!(MAKE_NAMESPACE_OBJECT);
77-
declare_runtime_global!(EXPORTS);
78-
declare_runtime_global!(COMPAT_GET_DEFAULT_EXPORT);
79-
declare_runtime_global!(CREATE_FAKE_NAMESPACE_OBJECT);
80-
declare_runtime_global!(NODE_MODULE_DECORATOR);
81-
declare_runtime_global!(ESM_MODULE_DECORATOR);
82-
declare_runtime_global!(SYSTEM_CONTEXT);
83-
declare_runtime_global!(THIS_AS_EXPORTS);
84-
declare_runtime_global!(CURRENT_REMOTE_GET_SCOPE);
85-
declare_runtime_global!(SHARE_SCOPE_MAP);
86-
declare_runtime_global!(INITIALIZE_SHARING);
87-
declare_runtime_global!(SCRIPT_NONCE);
88-
declare_runtime_global!(RELATIVE_URL);
89-
declare_runtime_global!(CHUNK_NAME);
90-
declare_runtime_global!(RUNTIME_ID);
91-
declare_runtime_global!(PREFETCH_CHUNK);
92-
declare_runtime_global!(PREFETCH_CHUNK_HANDLERS);
93-
declare_runtime_global!(PRELOAD_CHUNK);
94-
declare_runtime_global!(PRELOAD_CHUNK_HANDLERS);
95-
declare_runtime_global!(UNCAUGHT_ERROR_HANDLER);
96-
declare_runtime_global!(RSPACK_VERSION);
97-
declare_runtime_global!(HAS_CSS_MODULES);
98-
declare_runtime_global!(RSPACK_UNIQUE_ID);
99-
declare_runtime_global!(HAS_FETCH_PRIORITY);
100-
declare_runtime_global!(AMD_DEFINE);
101-
declare_runtime_global!(AMD_OPTIONS);
102-
declare_runtime_global!(ASYNC_MODULE_EXPORT_SYMBOL);
103-
declare_runtime_global!(MAKE_DEFERRED_NAMESPACE_OBJECT);
104-
declare_runtime_global!(MAKE_DEFERRED_NAMESPACE_OBJECT_SYMBOL);
105-
10629
to_js_map.shrink_to_fit();
10730
from_js_map.shrink_to_fit();
10831
(to_js_map, from_js_map)

crates/rspack_core/src/compilation/build_module_graph/module_executor/execute.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,9 @@ impl Task<ExecutorTaskContext> for ExecuteTask {
382382
let identifier = runtime_module.identifier();
383383
ExecutedRuntimeModule {
384384
identifier,
385-
name: runtime_module.name().to_string(),
385+
name: runtime_module
386+
.readable_identifier(&compilation.options.context)
387+
.into(),
386388
name_for_condition: runtime_module.name_for_condition().map(|n| n.to_string()),
387389
module_type: *runtime_module.module_type(),
388390
cacheable: !(runtime_module.full_hash() || runtime_module.dependent_hash()),

crates/rspack_core/src/stats/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1302,7 +1302,7 @@ impl Stats<'_> {
13021302
== 0;
13031303

13041304
stats.identifier = Some(module.identifier());
1305-
stats.name = Some(module.name().as_str().into());
1305+
stats.name = Some(module.readable_identifier(&self.compilation.options.context));
13061306
stats.name_for_condition = module.name_for_condition().map(|n| n.to_string());
13071307
stats.cacheable = Some(!(module.full_hash() || module.dependent_hash()));
13081308
stats.optional = Some(false);

crates/rspack_plugin_extract_css/src/runtime.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ impl RuntimeModule for CssLoadingRuntimeModule {
328328

329329
impl CssLoadingRuntimeModule {
330330
fn template_id(&self, id: TemplateId) -> String {
331-
let base_id = self.name().to_string();
331+
let base_id = self.id.to_string();
332332

333333
match id {
334334
TemplateId::Raw => base_id,

packages/rspack-test-tools/src/helper/hot-update/plugin.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ export class HotUpdatePlugin {
137137
}
138138

139139
apply(compiler: Compiler) {
140+
const RuntimeGlobals = compiler.rspack.RuntimeGlobals;
140141
const options = compiler.options;
141142
options.context = this.tempDir;
142143
options.module.rules ??= [];
@@ -160,7 +161,7 @@ export class HotUpdatePlugin {
160161
compilation.hooks.additionalTreeRuntimeRequirements.tap(
161162
PLUGIN_NAME,
162163
(_chunk: any, set: any) => {
163-
set.add(compiler.webpack.RuntimeGlobals.moduleCache);
164+
set.add(compiler.rspack.RuntimeGlobals.moduleCache);
164165
}
165166
);
166167
compilation.hooks.runtimeModule.tap(
@@ -169,9 +170,9 @@ export class HotUpdatePlugin {
169170
if (module.constructorName === "DefinePropertyGettersRuntimeModule") {
170171
module.source.source = Buffer.from(
171172
`
172-
__webpack_require__.d = function (exports, definition) {
173+
${RuntimeGlobals.definePropertyGetters} = function (exports, definition) {
173174
for (var key in definition) {
174-
if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
175+
if (${RuntimeGlobals.hasOwnProperty}(definition, key) && !${RuntimeGlobals.hasOwnProperty}(exports, key)) {
175176
Object.defineProperty(exports, key, { configurable: true, enumerable: true, get: definition[key] });
176177
}
177178
}

packages/rspack/etc/core.api.md

Lines changed: 88 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -2349,7 +2349,7 @@ interface ExecuteModuleArgument {
23492349
// @public (undocumented)
23502350
interface ExecuteModuleContext {
23512351
// (undocumented)
2352-
__webpack_require__: (id: string) => any;
2352+
[key: string]: (id: string) => any;
23532353
}
23542354

23552355
// @public (undocumented)
@@ -7115,81 +7115,93 @@ const RuntimeChunkPlugin: {
71157115
};
71167116

71177117
// @public (undocumented)
7118-
export const RuntimeGlobals: {
7119-
readonly require: "__webpack_require__";
7120-
readonly requireScope: "__webpack_require__.*";
7121-
readonly exports: "__webpack_exports__";
7122-
readonly thisAsExports: "top-level-this-exports";
7123-
readonly returnExportsFromRuntime: "return-exports-from-runtime";
7124-
readonly module: "module";
7125-
readonly moduleId: "module.id";
7126-
readonly moduleLoaded: "module.loaded";
7127-
readonly publicPath: "__webpack_require__.p";
7128-
readonly entryModuleId: "__webpack_require__.s";
7129-
readonly moduleCache: "__webpack_require__.c";
7130-
readonly moduleFactories: "__webpack_require__.m";
7131-
readonly moduleFactoriesAddOnly: "__webpack_require__.m (add only)";
7132-
readonly ensureChunk: "__webpack_require__.e";
7133-
readonly ensureChunkHandlers: "__webpack_require__.f";
7134-
readonly ensureChunkIncludeEntries: "__webpack_require__.f (include entries)";
7135-
readonly prefetchChunk: "__webpack_require__.E";
7136-
readonly prefetchChunkHandlers: "__webpack_require__.F";
7137-
readonly preloadChunk: "__webpack_require__.G";
7138-
readonly preloadChunkHandlers: "__webpack_require__.H";
7139-
readonly definePropertyGetters: "__webpack_require__.d";
7140-
readonly makeNamespaceObject: "__webpack_require__.r";
7141-
readonly createFakeNamespaceObject: "__webpack_require__.t";
7142-
readonly compatGetDefaultExport: "__webpack_require__.n";
7143-
readonly harmonyModuleDecorator: "__webpack_require__.hmd";
7144-
readonly nodeModuleDecorator: "__webpack_require__.nmd";
7145-
readonly getFullHash: "__webpack_require__.h";
7146-
readonly wasmInstances: "__webpack_require__.w";
7147-
readonly instantiateWasm: "__webpack_require__.v";
7148-
readonly uncaughtErrorHandler: "__webpack_require__.oe";
7149-
readonly scriptNonce: "__webpack_require__.nc";
7150-
readonly loadScript: "__webpack_require__.l";
7151-
readonly createScript: "__webpack_require__.ts";
7152-
readonly createScriptUrl: "__webpack_require__.tu";
7153-
readonly getTrustedTypesPolicy: "__webpack_require__.tt";
7154-
readonly hasFetchPriority: "has fetch priority";
7155-
readonly chunkName: "__webpack_require__.cn";
7156-
readonly runtimeId: "__webpack_require__.j";
7157-
readonly getChunkScriptFilename: "__webpack_require__.u";
7158-
readonly getChunkCssFilename: "__webpack_require__.k";
7159-
readonly hasCssModules: "has css modules";
7160-
readonly getChunkUpdateScriptFilename: "__webpack_require__.hu";
7161-
readonly getChunkUpdateCssFilename: "__webpack_require__.hk";
7162-
readonly startup: "__webpack_require__.x";
7163-
readonly startupNoDefault: "__webpack_require__.x (no default handler)";
7164-
readonly startupOnlyAfter: "__webpack_require__.x (only after)";
7165-
readonly startupOnlyBefore: "__webpack_require__.x (only before)";
7166-
readonly chunkCallback: "webpackChunk";
7167-
readonly startupEntrypoint: "__webpack_require__.X";
7168-
readonly onChunksLoaded: "__webpack_require__.O";
7169-
readonly externalInstallChunk: "__webpack_require__.C";
7170-
readonly interceptModuleExecution: "__webpack_require__.i";
7171-
readonly global: "__webpack_require__.g";
7172-
readonly shareScopeMap: "__webpack_require__.S";
7173-
readonly initializeSharing: "__webpack_require__.I";
7174-
readonly currentRemoteGetScope: "__webpack_require__.R";
7175-
readonly getUpdateManifestFilename: "__webpack_require__.hmrF";
7176-
readonly hmrDownloadManifest: "__webpack_require__.hmrM";
7177-
readonly hmrDownloadUpdateHandlers: "__webpack_require__.hmrC";
7178-
readonly hmrModuleData: "__webpack_require__.hmrD";
7179-
readonly hmrInvalidateModuleHandlers: "__webpack_require__.hmrI";
7180-
readonly hmrRuntimeStatePrefix: "__webpack_require__.hmrS";
7181-
readonly amdDefine: "__webpack_require__.amdD";
7182-
readonly amdOptions: "__webpack_require__.amdO";
7183-
readonly system: "__webpack_require__.System";
7184-
readonly hasOwnProperty: "__webpack_require__.o";
7185-
readonly systemContext: "__webpack_require__.y";
7186-
readonly baseURI: "__webpack_require__.b";
7187-
readonly relativeUrl: "__webpack_require__.U";
7188-
readonly asyncModule: "__webpack_require__.a";
7189-
readonly asyncModuleExportSymbol: "__webpack_require__.aE";
7190-
readonly makeDeferredNamespaceObject: "__webpack_require__.z";
7191-
readonly makeDeferredNamespaceObjectSymbol: "__webpack_require__.zS";
7192-
};
7118+
export const RuntimeGlobals: typeof RuntimeGlobals_2;
7119+
7120+
// @public (undocumented)
7121+
enum RuntimeGlobals_2 {
7122+
amdDefine = 65,
7123+
amdOptions = 66,
7124+
asyncModule = 72,
7125+
// (undocumented)
7126+
asyncModuleExportSymbol = 73,
7127+
baseURI = 70,
7128+
chunkCallback = 49,
7129+
chunkName = 36,
7130+
compatGetDefaultExport = 23,
7131+
createFakeNamespaceObject = 22,
7132+
createScript = 32,
7133+
createScriptUrl = 33,
7134+
currentRemoteGetScope = 58,
7135+
definePropertyGetters = 20,
7136+
ensureChunk = 13,
7137+
ensureChunkHandlers = 14,
7138+
ensureChunkIncludeEntries = 15,
7139+
entryModuleId = 9,
7140+
exports = 2,
7141+
externalInstallChunk = 53,
7142+
getChunkCssFilename = 39,
7143+
getChunkScriptFilename = 38,
7144+
getChunkUpdateCssFilename = 44,
7145+
getChunkUpdateScriptFilename = 43,
7146+
getFullHash = 26,
7147+
getTrustedTypesPolicy = 34,
7148+
getUpdateManifestFilename = 59,
7149+
global = 55,
7150+
harmonyModuleDecorator = 24,
7151+
hasCssModules = 41,
7152+
hasFetchPriority = 35,
7153+
hasOwnProperty = 68,
7154+
hmrDownloadManifest = 60,
7155+
hmrDownloadUpdateHandlers = 61,
7156+
hmrInvalidateModuleHandlers = 63,
7157+
hmrModuleData = 62,
7158+
hmrRuntimeStatePrefix = 64,
7159+
initializeSharing = 57,
7160+
instantiateWasm = 28,
7161+
interceptModuleExecution = 54,
7162+
loadScript = 31,
7163+
// (undocumented)
7164+
makeDeferredNamespaceObject = 74,
7165+
// (undocumented)
7166+
makeDeferredNamespaceObjectSymbol = 75,
7167+
makeNamespaceObject = 21,
7168+
module = 5,
7169+
moduleCache = 10,
7170+
moduleFactories = 11,
7171+
moduleFactoriesAddOnly = 12,
7172+
moduleId = 6,
7173+
moduleLoaded = 7,
7174+
nodeModuleDecorator = 25,
7175+
onChunksLoaded = 52,
7176+
prefetchChunk = 16,
7177+
prefetchChunkHandlers = 17,
7178+
preloadChunk = 18,
7179+
preloadChunkHandlers = 19,
7180+
publicPath = 8,
7181+
relativeUrl = 71,
7182+
require = 0,
7183+
requireScope = 1,
7184+
returnExportsFromRuntime = 4,
7185+
// @internal
7186+
rspackUniqueId = 42,
7187+
// @internal
7188+
rspackVersion = 40,
7189+
runtimeId = 37,
7190+
scriptNonce = 30,
7191+
shareScopeMap = 56,
7192+
startup = 45,
7193+
startupChunkDependencies = 51,
7194+
startupEntrypoint = 50,
7195+
// @deprecated (undocumented)
7196+
startupNoDefault = 46,
7197+
startupOnlyAfter = 47,
7198+
startupOnlyBefore = 48,
7199+
system = 67,
7200+
systemContext = 69,
7201+
thisAsExports = 3,
7202+
uncaughtErrorHandler = 29,
7203+
wasmInstances = 27
7204+
}
71937205

71947206
// @public (undocumented)
71957207
export class RuntimeModule {

packages/rspack/src/Compilation.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ export interface ExecuteModuleArgument {
124124
}
125125

126126
export interface ExecuteModuleContext {
127-
__webpack_require__: (id: string) => any;
127+
[key: string]: (id: string) => any;
128128
}
129129

130130
export interface KnownNormalizedStatsOptions {

packages/rspack/src/Compiler.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import { Logger } from "./logging/Logger";
4646
import { NormalModuleFactory } from "./NormalModuleFactory";
4747
import { ResolverFactory } from "./ResolverFactory";
4848
import { RuleSetCompiler } from "./RuleSetCompiler";
49+
import { createCompilerRuntimeGlobals } from "./RuntimeGlobals";
4950
import { Stats } from "./Stats";
5051
import {
5152
createCompilationHooksRegisters,
@@ -245,8 +246,15 @@ class Compiler {
245246
additionalPass: new liteTapable.AsyncSeriesHook([])
246247
};
247248

248-
this.webpack = rspack;
249-
this.rspack = rspack;
249+
const compilerRuntimeGlobals = createCompilerRuntimeGlobals(options);
250+
this.webpack = {
251+
...rspack,
252+
RuntimeGlobals: compilerRuntimeGlobals
253+
} as typeof rspack;
254+
this.rspack = {
255+
...rspack,
256+
RuntimeGlobals: compilerRuntimeGlobals
257+
} as typeof rspack;
250258
this.root = this;
251259
this.outputPath = "";
252260

packages/rspack/src/ExecuteModulePlugin.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { RuntimeGlobals } from ".";
21
import type { Compiler } from "./Compiler";
2+
import { RuntimeVariable, renderRuntimeVariables } from "./RuntimeGlobals";
33

44
export default class ExecuteModulePlugin {
55
apply(compiler: Compiler) {
@@ -19,7 +19,7 @@ export default class ExecuteModulePlugin {
1919

2020
try {
2121
const fn = vm.runInThisContext(
22-
`(function(module, __webpack_module__, __webpack_exports__, exports, ${RuntimeGlobals.require}) {\n${code}\n})`,
22+
`(function(module, ${renderRuntimeVariables(RuntimeVariable.Module, compiler.options)}, ${renderRuntimeVariables(RuntimeVariable.Exports, compiler.options)}, exports, ${renderRuntimeVariables(RuntimeVariable.Require, compiler.options)}) {\n${code}\n})`,
2323
{
2424
filename: moduleObject.id
2525
}
@@ -31,7 +31,12 @@ export default class ExecuteModulePlugin {
3131
moduleObject,
3232
moduleObject.exports,
3333
moduleObject.exports,
34-
context.__webpack_require__
34+
context[
35+
renderRuntimeVariables(
36+
RuntimeVariable.Require,
37+
compiler.options
38+
)
39+
]
3540
);
3641
} catch (e: any) {
3742
const err = e instanceof Error ? e : new Error(e);

0 commit comments

Comments
 (0)