Skip to content

Commit 2165f1b

Browse files
feat: using runtime_template to support output.environment (#9052)
- Introduced new runtime template in `runtime_template.rs` to support enhanced functionality. - Adjusted raw output handling in `raw_output.rs` for improved performance. - Updated various snapshot tests to reflect changes in output and ensure consistency. These changes aim to improve the overall type safety and reduce production size.
1 parent 876f50e commit 2165f1b

File tree

165 files changed

+677
-498
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

165 files changed

+677
-498
lines changed

crates/node_binding/binding.d.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1382,6 +1382,16 @@ export interface RawEnvironment {
13821382
const?: boolean
13831383
arrowFunction?: boolean
13841384
nodePrefixForCoreModules?: boolean
1385+
asyncFunction?: boolean
1386+
bigIntLiteral?: boolean
1387+
destructuring?: boolean
1388+
document?: boolean
1389+
dynamicImport?: boolean
1390+
forOf?: boolean
1391+
globalThis?: boolean
1392+
module?: boolean
1393+
optionalChaining?: boolean
1394+
templateLiteral?: boolean
13851395
}
13861396

13871397
export interface RawEvalDevToolModulePluginOptions {

crates/rspack/src/builder/mod.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2247,6 +2247,16 @@ impl OutputOptionsBuilder {
22472247
r#const: tp.and_then(|t| t.r#const),
22482248
arrow_function: tp.and_then(|t| t.arrow_function),
22492249
node_prefix_for_core_modules: tp.and_then(|t| t.node_prefix_for_core_modules),
2250+
async_function: tp.and_then(|t| t.async_function),
2251+
big_int_literal: tp.and_then(|t| t.big_int_literal),
2252+
destructuring: tp.and_then(|t| t.destructuring),
2253+
for_of: tp.and_then(|t| t.for_of),
2254+
global_this: tp.and_then(|t| t.global_this),
2255+
optional_chaining: tp.and_then(|t| t.optional_chaining),
2256+
document: tp.and_then(|t| t.document),
2257+
dynamic_import: tp.and_then(|t| t.dynamic_import),
2258+
template_literal: tp.and_then(|t| t.template_literal),
2259+
module: tp.and_then(|t| t.module),
22502260
};
22512261

22522262
OutputOptions {

crates/rspack_binding_values/src/raw_options/raw_output.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ pub struct RawEnvironment {
4646
pub r#const: Option<bool>,
4747
pub arrow_function: Option<bool>,
4848
pub node_prefix_for_core_modules: Option<bool>,
49+
pub async_function: Option<bool>,
50+
pub big_int_literal: Option<bool>,
51+
pub destructuring: Option<bool>,
52+
pub document: Option<bool>,
53+
pub dynamic_import: Option<bool>,
54+
pub for_of: Option<bool>,
55+
pub global_this: Option<bool>,
56+
pub module: Option<bool>,
57+
pub optional_chaining: Option<bool>,
58+
pub template_literal: Option<bool>,
4959
}
5060

5161
impl From<RawEnvironment> for Environment {
@@ -54,6 +64,16 @@ impl From<RawEnvironment> for Environment {
5464
r#const: value.r#const,
5565
arrow_function: value.arrow_function,
5666
node_prefix_for_core_modules: value.node_prefix_for_core_modules,
67+
async_function: value.async_function,
68+
big_int_literal: value.big_int_literal,
69+
destructuring: value.destructuring,
70+
document: value.document,
71+
dynamic_import: value.dynamic_import,
72+
for_of: value.for_of,
73+
global_this: value.global_this,
74+
module: value.module,
75+
optional_chaining: value.optional_chaining,
76+
template_literal: value.template_literal,
5777
}
5878
}
5979
}

crates/rspack_core/src/compiler/compilation.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ use crate::{
5151
DependencyType, Entry, EntryData, EntryOptions, EntryRuntime, Entrypoint, ExecuteModuleId,
5252
Filename, ImportVarMap, LocalFilenameFn, Logger, ModuleFactory, ModuleGraph, ModuleGraphPartial,
5353
ModuleIdentifier, ModuleIdsArtifact, PathData, ResolverFactory, RuntimeGlobals, RuntimeModule,
54-
RuntimeSpecMap, SharedPluginDriver, SideEffectsOptimizeArtifact, SourceType, Stats,
54+
RuntimeSpecMap, RuntimeTemplate, SharedPluginDriver, SideEffectsOptimizeArtifact, SourceType,
55+
Stats,
5556
};
5657

5758
pub type BuildDependency = (
@@ -180,6 +181,7 @@ pub struct Compilation {
180181
pub loader_resolver_factory: Arc<ResolverFactory>,
181182
pub named_chunks: HashMap<String, ChunkUkey>,
182183
pub named_chunk_groups: HashMap<String, ChunkGroupUkey>,
184+
pub runtime_template: RuntimeTemplate,
183185

184186
// artifact for infer_async_modules_plugin
185187
pub async_modules_artifact: AsyncModulesArtifact,
@@ -276,6 +278,7 @@ impl Compilation {
276278
Self {
277279
id: CompilationId::new(),
278280
hot_index: 0,
281+
runtime_template: RuntimeTemplate::new(options.output.environment),
279282
records,
280283
options,
281284
other_module_graph: None,

crates/rspack_core/src/init_fragment.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ fn first<C>(fragments: Vec<Box<dyn InitFragment<C>>>) -> Box<dyn InitFragment<C>
157157
pub trait InitFragmentRenderContext {
158158
fn add_runtime_requirements(&mut self, requirement: RuntimeGlobals);
159159
fn runtime_condition_expression(&mut self, runtime_condition: &RuntimeCondition) -> String;
160+
fn returning_function(&self, return_value: &str, args: &str) -> String;
160161
}
161162

162163
pub trait InitFragment<C>: IntoAny + DynHash + DynClone + Debug + Sync + Send {
@@ -269,6 +270,13 @@ impl InitFragmentRenderContext for GenerateContext<'_> {
269270
self.runtime_requirements,
270271
)
271272
}
273+
274+
fn returning_function(&self, return_value: &str, args: &str) -> String {
275+
self
276+
.compilation
277+
.runtime_template
278+
.returning_function(return_value, args)
279+
}
272280
}
273281

274282
pub struct ChunkRenderContext;
@@ -281,6 +289,10 @@ impl InitFragmentRenderContext for ChunkRenderContext {
281289
fn runtime_condition_expression(&mut self, _runtime_condition: &RuntimeCondition) -> String {
282290
unreachable!("should not call runtime condition expression in chunk render context")
283291
}
292+
293+
fn returning_function(&self, _return_value: &str, _args: &str) -> String {
294+
unreachable!("should not call returning function in chunk render context")
295+
}
284296
}
285297

286298
#[derive(Debug, Clone, Hash)]
@@ -359,7 +371,11 @@ impl<C: InitFragmentRenderContext> InitFragment<C> for ESMExportInitFragment {
359371
.iter()
360372
.map(|s| {
361373
let prop = property_name(&s.0)?;
362-
Ok(format!("{}: function() {{ return {}; }}", prop, s.1))
374+
Ok(format!(
375+
"{}: {}",
376+
prop,
377+
context.returning_function(&s.1, "")
378+
))
363379
})
364380
.collect::<Result<Vec<_>>>()?
365381
.join(",\n ")

crates/rspack_core/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ mod fake_namespace_object;
1818
mod template;
1919
pub use fake_namespace_object::*;
2020
pub use template::Template;
21+
mod runtime_template;
22+
pub use runtime_template::*;
2123
mod module_profile;
2224
pub use module_profile::*;
2325
use rspack_collections::Database;

crates/rspack_core/src/options/output.rs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,11 +468,21 @@ pub struct LibraryCustomUmdObject {
468468
pub root: Option<Vec<String>>,
469469
}
470470

471-
#[derive(Debug)]
471+
#[derive(Debug, Copy, Clone)]
472472
pub struct Environment {
473473
pub r#const: Option<bool>,
474474
pub arrow_function: Option<bool>,
475475
pub node_prefix_for_core_modules: Option<bool>,
476+
pub async_function: Option<bool>,
477+
pub big_int_literal: Option<bool>,
478+
pub destructuring: Option<bool>,
479+
pub document: Option<bool>,
480+
pub dynamic_import: Option<bool>,
481+
pub for_of: Option<bool>,
482+
pub global_this: Option<bool>,
483+
pub module: Option<bool>,
484+
pub optional_chaining: Option<bool>,
485+
pub template_literal: Option<bool>,
476486
}
477487

478488
impl Environment {
@@ -487,4 +497,44 @@ impl Environment {
487497
pub fn supports_node_prefix_for_core_modules(&self) -> bool {
488498
self.node_prefix_for_core_modules.unwrap_or_default()
489499
}
500+
501+
pub fn supports_async_function(&self) -> bool {
502+
self.async_function.unwrap_or_default()
503+
}
504+
505+
pub fn supports_big_int_literal(&self) -> bool {
506+
self.big_int_literal.unwrap_or_default()
507+
}
508+
509+
pub fn supports_destructuring(&self) -> bool {
510+
self.destructuring.unwrap_or_default()
511+
}
512+
513+
pub fn supports_document(&self) -> bool {
514+
self.document.unwrap_or_default()
515+
}
516+
517+
pub fn supports_dynamic_import(&self) -> bool {
518+
self.dynamic_import.unwrap_or_default()
519+
}
520+
521+
pub fn supports_for_of(&self) -> bool {
522+
self.for_of.unwrap_or_default()
523+
}
524+
525+
pub fn supports_global_this(&self) -> bool {
526+
self.global_this.unwrap_or_default()
527+
}
528+
529+
pub fn supports_module(&self) -> bool {
530+
self.module.unwrap_or_default()
531+
}
532+
533+
pub fn supports_optional_chaining(&self) -> bool {
534+
self.optional_chaining.unwrap_or_default()
535+
}
536+
537+
pub fn supports_template_literal(&self) -> bool {
538+
self.template_literal.unwrap_or_default()
539+
}
490540
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use std::fmt::Debug;
2+
3+
use crate::Environment;
4+
5+
pub struct RuntimeTemplate {
6+
environment: Environment,
7+
}
8+
9+
impl Debug for RuntimeTemplate {
10+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11+
f.debug_struct("runtime_template")
12+
.field("environment", &self.environment)
13+
.finish()
14+
}
15+
}
16+
17+
impl RuntimeTemplate {
18+
pub fn new(environment: Environment) -> Self {
19+
Self { environment }
20+
}
21+
22+
pub fn returning_function(&self, return_value: &str, args: &str) -> String {
23+
if self.environment.supports_arrow_function() {
24+
format!("({args}) => ({return_value})")
25+
} else {
26+
format!("function({args}) {{ return {return_value}; }}")
27+
}
28+
}
29+
30+
pub fn basic_function(&self, args: &str, body: &str) -> String {
31+
if self.environment.supports_arrow_function() {
32+
format!("({args}) => {{\n {body} \n}}")
33+
} else {
34+
format!("function({args}) {{\n {body} \n}}")
35+
}
36+
}
37+
}

packages/rspack-test-tools/tests/__snapshots__/NewCodeSplitting-stats-output.test.js.snap

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ Rspack x.x.x compiled successfully in X s
9898
9999
exports[`new code splitting stats output new code splitting stats output/filename should print correct stats for: NewCodeSplittingStatsOutput 1`] = `
100100
asset 909.xxxx.js 9.14 KiB [emitted] (name: main)
101-
asset 521.xxxx.js 337 bytes [emitted]
101+
asset 521.xxxx.js 322 bytes [emitted]
102102
runtime modules 7.54 KiB 11 modules
103103
cacheable modules 70 bytes
104104
./index.js 38 bytes [built] [code generated]
@@ -219,7 +219,7 @@ Rspack compiled with 1 error
219219
220220
exports[`new code splitting stats output new code splitting stats output/named-chunk-group should print correct stats for: NewCodeSplittingStatsOutput 1`] = `
221221
Entrypoint main 9.13 KiB = main.js
222-
Chunk Group cimanyd 337 bytes = cimanyd.js
222+
Chunk Group cimanyd 322 bytes = cimanyd.js
223223
`;
224224
225225
exports[`new code splitting stats output new code splitting stats output/nonexistent-import-source-error should print correct stats for: NewCodeSplittingStatsOutput 1`] = `
@@ -438,7 +438,7 @@ Rspack x.x.x compiled successfully in X s
438438
`;
439439
440440
exports[`new code splitting stats output new code splitting stats output/simple-export should print correct stats for: NewCodeSplittingStatsOutput 1`] = `
441-
asset bundle.js 1.71 KiB [emitted] (name: main)
441+
asset bundle.js 1.69 KiB [emitted] (name: main)
442442
runtime modules 677 bytes 3 modules
443443
./index.js 26 bytes [built] [code generated]
444444
Rspack x.x.x compiled successfully in X s

packages/rspack-test-tools/tests/__snapshots__/StatsOutput.test.js.snap

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ Rspack x.x.x compiled successfully in X s
9898
9999
exports[`statsOutput statsOutput/filename should print correct stats for 1`] = `
100100
asset 909.xxxx.js 9.14 KiB [emitted] (name: main)
101-
asset 521.xxxx.js 337 bytes [emitted]
101+
asset 521.xxxx.js 322 bytes [emitted]
102102
runtime modules 7.54 KiB 11 modules
103103
cacheable modules 70 bytes
104104
./index.js 38 bytes [built] [code generated]
@@ -219,7 +219,7 @@ Rspack compiled with 1 error
219219
220220
exports[`statsOutput statsOutput/named-chunk-group should print correct stats for 1`] = `
221221
Entrypoint main 9.13 KiB = main.js
222-
Chunk Group cimanyd 337 bytes = cimanyd.js
222+
Chunk Group cimanyd 322 bytes = cimanyd.js
223223
`;
224224
225225
exports[`statsOutput statsOutput/nonexistent-import-source-error should print correct stats for 1`] = `
@@ -438,7 +438,7 @@ Rspack x.x.x compiled successfully in X s
438438
`;
439439
440440
exports[`statsOutput statsOutput/simple-export should print correct stats for 1`] = `
441-
asset bundle.js 1.71 KiB [emitted] (name: main)
441+
asset bundle.js 1.69 KiB [emitted] (name: main)
442442
runtime modules 677 bytes 3 modules
443443
./index.js 26 bytes [built] [code generated]
444444
Rspack x.x.x compiled successfully in X s

0 commit comments

Comments
 (0)