Skip to content

Commit 46a54da

Browse files
authored
refactor: import external should not create needless external module (#12064)
1 parent 55c107d commit 46a54da

File tree

13 files changed

+108
-125
lines changed

13 files changed

+108
-125
lines changed

Cargo.lock

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/node_binding/napi-binding.d.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2732,12 +2732,6 @@ export interface RawRslibPluginOptions {
27322732
* @default `false`
27332733
*/
27342734
interceptApiPlugin?: boolean
2735-
/**
2736-
* Use the compact runtime for dynamic import from `modern-module`, commonly used in CommonJS output.
2737-
* This field should not be set to `true` when using `modern-module` with ESM output, as it is already in use.
2738-
* @default `false`
2739-
*/
2740-
compactExternalModuleDynamicImport?: boolean
27412735
/**
27422736
* Add shims for javascript/esm modules
27432737
* @default `false`

crates/rspack_binding_api/src/rslib.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@ pub struct RawRslibPluginOptions {
77
/// Intercept partial parse hooks of APIPlugin, expect some statements not to be parsed as API.
88
/// @default `false`
99
pub intercept_api_plugin: Option<bool>,
10-
/// Use the compact runtime for dynamic import from `modern-module`, commonly used in CommonJS output.
11-
/// This field should not be set to `true` when using `modern-module` with ESM output, as it is already in use.
12-
/// @default `false`
13-
pub compact_external_module_dynamic_import: Option<bool>,
1410
/// Add shims for javascript/esm modules
1511
/// @default `false`
1612
pub force_node_shims: Option<bool>,
@@ -20,9 +16,6 @@ impl From<RawRslibPluginOptions> for RslibPluginOptions {
2016
fn from(value: RawRslibPluginOptions) -> Self {
2117
Self {
2218
intercept_api_plugin: value.intercept_api_plugin.unwrap_or_default(),
23-
compact_external_module_dynamic_import: value
24-
.compact_external_module_dynamic_import
25-
.unwrap_or_default(),
2619
force_node_shims: value.force_node_shims.unwrap_or_default(),
2720
}
2821
}

crates/rspack_plugin_library/src/lib.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@ mod utils;
1111
pub use amd_library_plugin::AmdLibraryPlugin;
1212
pub use assign_library_plugin::*;
1313
pub use export_property_library_plugin::ExportPropertyLibraryPlugin;
14-
pub use modern_module::ModernModuleImportDependencyTemplate;
15-
pub use modern_module_library_plugin::replace_import_dependencies_for_external_modules;
1614
use rspack_core::{BoxPlugin, PluginExt};
1715
pub use system_library_plugin::SystemLibraryPlugin;
1816
pub use umd_library_plugin::UmdLibraryPlugin;
Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,2 @@
1-
mod import_dependency;
21
mod reexport_star_external_dependency;
3-
4-
pub use import_dependency::*;
52
pub use reexport_star_external_dependency::*;

crates/rspack_plugin_library/src/modern_module_library_plugin.rs

Lines changed: 5 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ use rspack_collections::IdentifierMap;
44
use rspack_core::{
55
BoxDependency, ChunkUkey, CodeGenerationExportsFinalNames, Compilation,
66
CompilationOptimizeChunkModules, CompilationParams, CompilerCompilation, CompilerFinishMake,
7-
ConcatenatedModule, ConcatenatedModuleExportsDefinitions, DependenciesBlock, Dependency,
8-
DependencyId, ExportsType, LibraryOptions, ModuleDependency, ModuleGraph, ModuleIdentifier,
9-
Plugin, PrefetchExportsInfoMode, RuntimeSpec, UsedNameItem,
7+
ConcatenatedModule, ConcatenatedModuleExportsDefinitions, DependencyId, ExportsType,
8+
LibraryOptions, ModuleGraph, ModuleIdentifier, Plugin, PrefetchExportsInfoMode, RuntimeSpec,
9+
UsedNameItem,
1010
rspack_sources::{ConcatSource, RawStringSource, SourceExt},
1111
to_identifier,
1212
};
@@ -16,82 +16,18 @@ use rspack_hook::{plugin, plugin_hook};
1616
use rspack_plugin_javascript::{
1717
ConcatConfiguration, JavascriptModulesChunkHash, JavascriptModulesRenderStartup, JsPlugin,
1818
ModuleConcatenationPlugin, RenderSource,
19-
dependency::{
20-
ESMExportImportedSpecifierDependency, ESMImportSideEffectDependency, ImportDependency,
21-
},
19+
dependency::{ESMExportImportedSpecifierDependency, ESMImportSideEffectDependency},
2220
};
2321
use rustc_hash::FxHashSet as HashSet;
2422

2523
use super::modern_module::ModernModuleReexportStarExternalDependency;
2624
use crate::{
27-
modern_module::{
28-
ModernModuleImportDependency, ModernModuleImportDependencyTemplate,
29-
ModernModuleReexportStarExternalDependencyTemplate,
30-
},
25+
modern_module::ModernModuleReexportStarExternalDependencyTemplate,
3126
utils::{COMMON_LIBRARY_NAME_MESSAGE, get_options_for_chunk},
3227
};
3328

3429
const PLUGIN_NAME: &str = "rspack.ModernModuleLibraryPlugin";
3530

36-
/// Replaces ImportDependency instances with ModernModuleImportDependency for external modules.
37-
/// This function iterates through all modules and their blocks to find ImportDependencies
38-
/// that point to external modules, then creates ModernModuleImportDependency replacements.
39-
pub fn replace_import_dependencies_for_external_modules(
40-
compilation: &mut Compilation,
41-
) -> Result<()> {
42-
let mg = compilation.get_module_graph();
43-
let mut deps_to_replace: Vec<BoxDependency> = Vec::new();
44-
45-
for module in mg.modules().values() {
46-
for block_id in module.get_blocks() {
47-
let Some(block) = mg.block_by_id(block_id) else {
48-
continue;
49-
};
50-
for block_dep_id in block.get_dependencies() {
51-
let block_dep = mg.dependency_by_id(block_dep_id);
52-
if let Some(block_dep) = block_dep
53-
&& let Some(import_dependency) = block_dep.as_any().downcast_ref::<ImportDependency>()
54-
{
55-
let import_dep_connection = mg.connection_by_dependency_id(block_dep_id);
56-
if let Some(import_dep_connection) = import_dep_connection {
57-
// Try find the connection with a import dependency pointing to an external module.
58-
// If found, remove the connection and add a new import dependency to performs the external module ID replacement.
59-
let import_module_id = import_dep_connection.module_identifier();
60-
let Some(import_module) = mg.module_by_identifier(import_module_id) else {
61-
continue;
62-
};
63-
64-
if let Some(external_module) = import_module.as_external_module() {
65-
let new_dep = ModernModuleImportDependency::new(
66-
*block_dep.id(),
67-
import_dependency.request().into(),
68-
external_module.request.clone(),
69-
external_module.external_type.clone(),
70-
import_dependency.range,
71-
import_dependency.get_attributes().cloned(),
72-
import_dependency.comments.clone(),
73-
);
74-
75-
deps_to_replace.push(Box::new(new_dep));
76-
}
77-
}
78-
}
79-
}
80-
}
81-
}
82-
83-
let mut mg = compilation.get_module_graph_mut();
84-
for dep in deps_to_replace {
85-
let dep_id = dep.id();
86-
// remove connection
87-
mg.revoke_dependency(dep_id, false);
88-
// overwrite dependency
89-
mg.add_dependency(dep);
90-
}
91-
92-
Ok(())
93-
}
94-
9531
#[plugin]
9632
#[derive(Debug, Default)]
9733
pub struct ModernModuleLibraryPlugin;
@@ -489,8 +425,6 @@ pub fn render_as_default_export_impl(exports: &[(String, Option<String>)]) -> St
489425

490426
#[plugin_hook(CompilerFinishMake for ModernModuleLibraryPlugin)]
491427
async fn finish_make(&self, compilation: &mut Compilation) -> Result<()> {
492-
// Replace ImportDependency instances with ModernModuleImportDependency for external modules
493-
replace_import_dependencies_for_external_modules(compilation)?;
494428
self.preserve_reexports_star(compilation)?;
495429

496430
Ok(())
@@ -527,10 +461,6 @@ async fn compilation(
527461
hooks.render_startup.tap(render_startup::new(self));
528462
hooks.chunk_hash.tap(js_chunk_hash::new(self));
529463

530-
compilation.set_dependency_template(
531-
ModernModuleImportDependencyTemplate::template_type(),
532-
Arc::new(ModernModuleImportDependencyTemplate::default()),
533-
);
534464
compilation.set_dependency_template(
535465
ModernModuleReexportStarExternalDependencyTemplate::template_type(),
536466
Arc::new(ModernModuleReexportStarExternalDependencyTemplate::default()),

crates/rspack_plugin_rslib/Cargo.toml

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@ version.workspace = true
88
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
99

1010
[dependencies]
11+
rspack_cacheable = { workspace = true }
1112
rspack_core = { workspace = true }
1213
rspack_error = { workspace = true }
1314
rspack_hook = { workspace = true }
1415
rspack_plugin_javascript = { workspace = true }
15-
rspack_plugin_library = { workspace = true }
16-
swc_core = { workspace = true }
17-
tracing = { workspace = true }
16+
17+
serde_json = { workspace = true }
18+
swc_core = { workspace = true }
19+
tracing = { workspace = true }
1820

1921
[package.metadata.cargo-shear]
2022
ignored = ["tracing"]

crates/rspack_plugin_library/src/modern_module/import_dependency.rs renamed to crates/rspack_plugin_rslib/src/import_dependency.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use swc_core::ecma::atoms::Atom;
1010

1111
#[cacheable]
1212
#[derive(Debug, Clone)]
13-
pub struct ModernModuleImportDependency {
13+
pub struct RslibImportDependency {
1414
id: DependencyId,
1515
#[cacheable(with=AsPreset)]
1616
request: Atom,
@@ -23,7 +23,7 @@ pub struct ModernModuleImportDependency {
2323
pub comments: Vec<(bool, String)>,
2424
}
2525

26-
impl ModernModuleImportDependency {
26+
impl RslibImportDependency {
2727
pub fn new(
2828
id: DependencyId,
2929
request: Atom,
@@ -50,7 +50,7 @@ impl ModernModuleImportDependency {
5050
}
5151

5252
#[cacheable_dyn]
53-
impl Dependency for ModernModuleImportDependency {
53+
impl Dependency for RslibImportDependency {
5454
fn id(&self) -> &DependencyId {
5555
&self.id
5656
}
@@ -81,7 +81,7 @@ impl Dependency for ModernModuleImportDependency {
8181
}
8282

8383
#[cacheable_dyn]
84-
impl ModuleDependency for ModernModuleImportDependency {
84+
impl ModuleDependency for RslibImportDependency {
8585
fn request(&self) -> &str {
8686
&self.request
8787
}
@@ -100,24 +100,24 @@ impl ModuleDependency for ModernModuleImportDependency {
100100
}
101101

102102
#[cacheable_dyn]
103-
impl DependencyCodeGeneration for ModernModuleImportDependency {
103+
impl DependencyCodeGeneration for RslibImportDependency {
104104
fn dependency_template(&self) -> Option<DependencyTemplateType> {
105-
Some(ModernModuleImportDependencyTemplate::template_type())
105+
Some(RslibDependencyTemplate::template_type())
106106
}
107107
}
108108

109-
impl AsContextDependency for ModernModuleImportDependency {}
109+
impl AsContextDependency for RslibImportDependency {}
110110

111111
#[cacheable]
112112
#[derive(Debug, Clone, Default)]
113-
pub struct ModernModuleImportDependencyTemplate;
114-
impl ModernModuleImportDependencyTemplate {
113+
pub struct RslibDependencyTemplate;
114+
impl RslibDependencyTemplate {
115115
pub fn template_type() -> DependencyTemplateType {
116-
DependencyTemplateType::Custom("ModernModuleImportDependency")
116+
DependencyTemplateType::Custom("RslibImportDependency")
117117
}
118118
}
119119

120-
impl DependencyTemplate for ModernModuleImportDependencyTemplate {
120+
impl DependencyTemplate for RslibDependencyTemplate {
121121
fn render(
122122
&self,
123123
dep: &dyn DependencyCodeGeneration,
@@ -126,10 +126,8 @@ impl DependencyTemplate for ModernModuleImportDependencyTemplate {
126126
) {
127127
let dep = dep
128128
.as_any()
129-
.downcast_ref::<ModernModuleImportDependency>()
130-
.expect(
131-
"ModernModuleImportDependencyTemplate should be used for ModernModuleImportDependency",
132-
);
129+
.downcast_ref::<RslibImportDependency>()
130+
.expect("RslibDependencyTemplate should be used for RslibImportDependency");
133131

134132
let request_and_external_type = match &dep.target_request {
135133
ExternalRequest::Single(request) => (Some(request), &dep.external_type),
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
use rspack_core::{BoxDependency, Compilation, DependenciesBlock, Dependency, ModuleDependency};
2+
use rspack_error::Result;
3+
use rspack_plugin_javascript::dependency::ImportDependency;
4+
5+
use crate::import_dependency::RslibImportDependency;
6+
7+
/// Replaces ImportDependency instances with RslibImportDependency for external modules.
8+
/// This function iterates through all modules and their blocks to find ImportDependencies
9+
/// that point to external modules, then creates RslibImportDependency replacements.
10+
pub fn replace_import_dependencies_for_external_modules(
11+
compilation: &mut Compilation,
12+
) -> Result<()> {
13+
let mg = compilation.get_module_graph();
14+
let mut deps_to_replace: Vec<BoxDependency> = Vec::new();
15+
16+
for module in mg.modules().values() {
17+
for block_id in module.get_blocks() {
18+
let Some(block) = mg.block_by_id(block_id) else {
19+
continue;
20+
};
21+
for block_dep_id in block.get_dependencies() {
22+
let block_dep = mg.dependency_by_id(block_dep_id);
23+
if let Some(block_dep) = block_dep
24+
&& let Some(import_dependency) = block_dep.as_any().downcast_ref::<ImportDependency>()
25+
{
26+
let import_dep_connection = mg.connection_by_dependency_id(block_dep_id);
27+
if let Some(import_dep_connection) = import_dep_connection {
28+
// Try find the connection with a import dependency pointing to an external module.
29+
// If found, remove the connection and add a new import dependency to performs the external module ID replacement.
30+
let import_module_id = import_dep_connection.module_identifier();
31+
let Some(import_module) = mg.module_by_identifier(import_module_id) else {
32+
continue;
33+
};
34+
35+
if let Some(external_module) = import_module.as_external_module() {
36+
let new_dep = RslibImportDependency::new(
37+
*block_dep.id(),
38+
import_dependency.request().into(),
39+
external_module.request.clone(),
40+
external_module.external_type.clone(),
41+
import_dependency.range,
42+
import_dependency.get_attributes().cloned(),
43+
import_dependency.comments.clone(),
44+
);
45+
46+
deps_to_replace.push(Box::new(new_dep));
47+
}
48+
}
49+
}
50+
}
51+
}
52+
}
53+
54+
let mut mg = compilation.get_module_graph_mut();
55+
for dep in deps_to_replace {
56+
let dep_id = dep.id();
57+
// remove connection
58+
mg.revoke_dependency(dep_id, false);
59+
// overwrite dependency
60+
mg.add_dependency(dep);
61+
}
62+
63+
Ok(())
64+
}
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1+
mod import_dependency;
2+
mod import_external;
13
mod parser_plugin;
24
mod plugin;
3-
45
pub use plugin::*;

0 commit comments

Comments
 (0)