From 923e999b8b7273d8966ae76c15a537a88448b36e Mon Sep 17 00:00:00 2001 From: Gengkun Date: Thu, 21 Mar 2024 20:10:58 +0800 Subject: [PATCH] refactor: finish make and finish modules hook (#5990) --- Cargo.lock | 1 + crates/node_binding/binding.d.ts | 4 +- crates/node_binding/src/hook.rs | 4 - .../node_binding/src/plugins/interceptor.rs | 70 +++++++- crates/node_binding/src/plugins/mod.rs | 54 +++--- .../src/options/raw_builtins/mod.rs | 4 +- crates/rspack_binding_values/src/hooks.rs | 4 - .../rspack_core/src/compiler/compilation.rs | 8 +- crates/rspack_core/src/compiler/mod.rs | 8 +- crates/rspack_core/src/plugin/api.rs | 8 - .../rspack_core/src/plugin/plugin_driver.rs | 27 +-- .../plugin/flag_dependency_exports_plugin.rs | 29 ++- .../src/plugin/infer_async_modules_plugin.rs | 110 +++++++----- crates/rspack_plugin_library/Cargo.toml | 1 + .../src/assign_library_plugin.rs | 143 ++++++++------- .../src/export_property_library_plugin.rs | 165 ++++++++++-------- .../src/sharing/provide_shared_plugin.rs | 56 +++--- crates/rspack_plugin_progress/src/lib.rs | 42 +++-- crates/rspack_testing/src/test_config.rs | 2 +- packages/rspack/src/Compilation.ts | 4 +- packages/rspack/src/Compiler.ts | 31 ++-- 21 files changed, 439 insertions(+), 336 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 562a56185d9..a7f563b2a57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3565,6 +3565,7 @@ dependencies = [ "regex", "rspack_core", "rspack_error", + "rspack_hook", "rspack_identifier", "serde_json", ] diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index e8b9a8fbf65..f705aa33b9b 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -317,8 +317,6 @@ export interface JsHooks { afterOptimizeModules: (compilation: JsCompilation) => void optimizeTree: () => void optimizeChunkModules: (compilation: JsCompilation) => void - finishModules: (compilation: JsCompilation) => void - finishMake: (compilation: JsCompilation) => void afterResolve: (data: AfterResolveData) => Promise<(boolean | void | AfterResolveCreateData)[]> contextModuleFactoryBeforeResolve: (data: JsBeforeResolveArgs) => Promise contextModuleFactoryAfterResolve: (data: AfterResolveData) => Promise @@ -1283,12 +1281,14 @@ export interface RegisterJsTaps { registerCompilerThisCompilationTaps: (stages: Array) => Array<{ function: ((arg: JsCompilation) => void); stage: number; }> registerCompilerCompilationTaps: (stages: Array) => Array<{ function: ((arg: JsCompilation) => void); stage: number; }> registerCompilerMakeTaps: (stages: Array) => Array<{ function: ((arg: JsCompilation) => Promise); stage: number; }> + registerCompilerFinishMakeTaps: (stages: Array) => Array<{ function: ((arg: JsCompilation) => void); stage: number; }> registerCompilerShouldEmitTaps: (stages: Array) => Array<{ function: ((arg: JsCompilation) => boolean | undefined); stage: number; }> registerCompilationBuildModuleTaps: (stages: Array) => Array<{ function: ((arg: JsModule) => void); stage: number; }> registerCompilationStillValidModuleTaps: (stages: Array) => Array<{ function: ((arg: JsModule) => void); stage: number; }> registerCompilationSucceedModuleTaps: (stages: Array) => Array<{ function: ((arg: JsModule) => void); stage: number; }> registerCompilationExecuteModuleTaps: (stages: Array) => Array<{ function: ((arg: JsExecuteModuleArg) => void); stage: number; }> registerCompilationRuntimeModuleTaps: (stages: Array) => Array<{ function: ((arg: JsRuntimeModuleArg) => JsRuntimeModule | undefined); stage: number; }> + registerCompilationFinishModulesTaps: (stages: Array) => Array<{ function: ((arg: JsCompilation) => Promise); stage: number; }> registerCompilationChunkAssetTaps: (stages: Array) => Array<{ function: ((arg: JsChunkAssetArgs) => void); stage: number; }> registerCompilationProcessAssetsTaps: (stages: Array) => Array<{ function: ((arg: JsCompilation) => Promise); stage: number; }> registerNormalModuleFactoryBeforeResolveTaps: (stages: Array) => Array<{ function: ((arg: JsBeforeResolveArgs) => Promise<[boolean | undefined, JsBeforeResolveArgs]>); stage: number; }> diff --git a/crates/node_binding/src/hook.rs b/crates/node_binding/src/hook.rs index 85be940e15f..4bf46fa5512 100644 --- a/crates/node_binding/src/hook.rs +++ b/crates/node_binding/src/hook.rs @@ -3,13 +3,11 @@ use std::sync::RwLock; /// rust support hooks #[derive(PartialEq)] pub enum Hook { - FinishMake, AfterProcessAssets, Emit, AssetEmitted, AfterEmit, OptimizeChunkModules, - FinishModules, OptimizeModules, AfterOptimizeModules, OptimizeTree, @@ -23,13 +21,11 @@ pub enum Hook { impl From for Hook { fn from(s: String) -> Self { match s.as_str() { - "finishMake" => Hook::FinishMake, "afterProcessAssets" => Hook::AfterProcessAssets, "emit" => Hook::Emit, "assetEmitted" => Hook::AssetEmitted, "afterEmit" => Hook::AfterEmit, "optimizeChunkModules" => Hook::OptimizeChunkModules, - "finishModules" => Hook::FinishModules, "optimizeModules" => Hook::OptimizeModules, "afterOptimizeModules" => Hook::AfterOptimizeModules, "optimizeTree" => Hook::OptimizeTree, diff --git a/crates/node_binding/src/plugins/interceptor.rs b/crates/node_binding/src/plugins/interceptor.rs index d9f4fac7415..422337e2363 100644 --- a/crates/node_binding/src/plugins/interceptor.rs +++ b/crates/node_binding/src/plugins/interceptor.rs @@ -13,10 +13,11 @@ use rspack_binding_values::{ use rspack_core::{ rspack_sources::SourceExt, BeforeResolveArgs, BoxModule, Chunk, ChunkUkey, CodeGenerationResults, Compilation, CompilationBuildModuleHook, CompilationChunkAssetHook, CompilationExecuteModuleHook, - CompilationParams, CompilationProcessAssetsHook, CompilationRuntimeModuleHook, - CompilationStillValidModuleHook, CompilationSucceedModuleHook, CompilerCompilationHook, - CompilerMakeHook, CompilerShouldEmitHook, CompilerThisCompilationHook, ExecuteModuleId, - MakeParam, ModuleIdentifier, NormalModuleFactoryBeforeResolveHook, + CompilationFinishModulesHook, CompilationParams, CompilationProcessAssetsHook, + CompilationRuntimeModuleHook, CompilationStillValidModuleHook, CompilationSucceedModuleHook, + CompilerCompilationHook, CompilerFinishMakeHook, CompilerMakeHook, CompilerShouldEmitHook, + CompilerThisCompilationHook, ExecuteModuleId, MakeParam, ModuleIdentifier, + NormalModuleFactoryBeforeResolveHook, }; use rspack_hook::{ AsyncSeries, AsyncSeries2, AsyncSeries3, AsyncSeriesBail, Hook, Interceptor, SyncSeries4, @@ -167,6 +168,13 @@ impl RegisterJsTapsInner { } } +/// define js taps register +/// cache: add cache for register function, used for `before_resolve` or `build_module` +/// which run register function multiple times for every module, cache will ensure +/// it only run once. +/// sync: synchronously/blocking call the register function, most of the register shouldn't +/// be sync since calling a ThreadsafeFunction is async, for now it's only used by +/// execute_module, which strongly required sync call. macro_rules! define_register { ($name:ident, tap = $tap_name:ident<$arg:ty, $ret:ty> @ $tap_hook:ty, cache = $cache:literal, sync = $sync:tt,) => { define_register!(@BASE $name, $tap_name<$arg, $ret> @ $tap_hook, $cache, $sync); @@ -249,6 +257,10 @@ pub struct RegisterJsTaps { ts_type = "(stages: Array) => Array<{ function: ((arg: JsCompilation) => Promise); stage: number; }>" )] pub register_compiler_make_taps: RegisterFunction>, + #[napi( + ts_type = "(stages: Array) => Array<{ function: ((arg: JsCompilation) => void); stage: number; }>" + )] + pub register_compiler_finish_make_taps: RegisterFunction>, #[napi( ts_type = "(stages: Array) => Array<{ function: ((arg: JsCompilation) => boolean | undefined); stage: number; }>" )] @@ -274,6 +286,10 @@ pub struct RegisterJsTaps { )] pub register_compilation_runtime_module_taps: RegisterFunction>, + #[napi( + ts_type = "(stages: Array) => Array<{ function: ((arg: JsCompilation) => Promise); stage: number; }>" + )] + pub register_compilation_finish_modules_taps: RegisterFunction>, #[napi( ts_type = "(stages: Array) => Array<{ function: ((arg: JsChunkAssetArgs) => void); stage: number; }>" )] @@ -308,6 +324,12 @@ define_register!( cache = false, sync = false, ); +define_register!( + RegisterCompilerFinishMakeTaps, + tap = CompilerFinishMakeTap> @ CompilerFinishMakeHook, + cache = false, + sync = false, +); define_register!( RegisterCompilerShouldEmitTaps, tap = CompilerShouldEmitTap> @ CompilerShouldEmitHook, @@ -340,6 +362,12 @@ define_register!( cache = false, sync = true, ); +define_register!( + RegisterCompilationFinishModulesTaps, + tap = CompilationFinishModulesTap> @ CompilationFinishModulesHook, + cache = false, + sync = false, +); define_register!( RegisterCompilationRuntimeModuleTaps, tap = CompilationRuntimeModuleTap> @ CompilationRuntimeModuleHook, @@ -428,6 +456,23 @@ impl AsyncSeries2> for CompilerMakeTap { } } +#[async_trait] +impl AsyncSeries for CompilerFinishMakeTap { + async fn run(&self, compilation: &mut Compilation) -> rspack_error::Result<()> { + // SAFETY: + // 1. `Compiler` is stored on the heap and pinned in binding crate. + // 2. `Compilation` outlives `JsCompilation` and `Compiler` outlives `Compilation`. + // 3. `JsCompilation` was replaced everytime a new `Compilation` was created before getting accessed. + let compilation = unsafe { JsCompilation::from_compilation(compilation) }; + + self.function.call_with_promise(compilation).await + } + + fn stage(&self) -> i32 { + self.stage + } +} + #[async_trait] impl AsyncSeriesBail for CompilerShouldEmitTap { async fn run(&self, compilation: &mut Compilation) -> rspack_error::Result> { @@ -511,6 +556,23 @@ impl SyncSeries4 for CompilationFinishModulesTap { + async fn run(&self, compilation: &mut Compilation) -> rspack_error::Result<()> { + // SAFETY: + // 1. `Compiler` is stored on the heap and pinned in binding crate. + // 2. `Compilation` outlives `JsCompilation` and `Compiler` outlives `Compilation`. + // 3. `JsCompilation` was replaced everytime a new `Compilation` was created before getting accessed. + let compilation = unsafe { JsCompilation::from_compilation(compilation) }; + + self.function.call_with_promise(compilation).await + } + + fn stage(&self) -> i32 { + self.stage + } +} + #[async_trait] impl AsyncSeries3 for CompilationRuntimeModuleTap { async fn run( diff --git a/crates/node_binding/src/plugins/mod.rs b/crates/node_binding/src/plugins/mod.rs index 4717843a48d..ce54539a71a 100644 --- a/crates/node_binding/src/plugins/mod.rs +++ b/crates/node_binding/src/plugins/mod.rs @@ -22,8 +22,10 @@ use rspack_hook::Hook as _; use self::interceptor::RegisterCompilationBuildModuleTaps; use self::interceptor::RegisterCompilationChunkAssetTaps; +use self::interceptor::RegisterCompilationFinishModulesTaps; use self::interceptor::RegisterCompilationStillValidModuleTaps; use self::interceptor::RegisterCompilationSucceedModuleTaps; +use self::interceptor::RegisterCompilerFinishMakeTaps; use self::interceptor::{ RegisterCompilationExecuteModuleTaps, RegisterCompilationProcessAssetsTaps, RegisterCompilationRuntimeModuleTaps, RegisterCompilerCompilationTaps, RegisterCompilerMakeTaps, @@ -43,11 +45,13 @@ pub struct JsHooksAdapterPlugin { register_compiler_this_compilation_taps: RegisterCompilerThisCompilationTaps, register_compiler_compilation_taps: RegisterCompilerCompilationTaps, register_compiler_make_taps: RegisterCompilerMakeTaps, + register_compiler_finish_make_taps: RegisterCompilerFinishMakeTaps, register_compiler_should_emit_taps: RegisterCompilerShouldEmitTaps, register_compilation_build_module_taps: RegisterCompilationBuildModuleTaps, register_compilation_still_valid_module_taps: RegisterCompilationStillValidModuleTaps, register_compilation_succeed_module_taps: RegisterCompilationSucceedModuleTaps, register_compilation_execute_module_taps: RegisterCompilationExecuteModuleTaps, + register_compilation_finish_modules_taps: RegisterCompilationFinishModulesTaps, register_compilation_runtime_module_taps: RegisterCompilationRuntimeModuleTaps, register_compilation_chunk_asset_taps: RegisterCompilationChunkAssetTaps, register_compilation_process_assets_taps: RegisterCompilationProcessAssetsTaps, @@ -96,6 +100,11 @@ impl rspack_core::Plugin for JsHooksAdapterPlugin { .compiler_hooks .make .intercept(self.register_compiler_make_taps.clone()); + ctx + .context + .compiler_hooks + .finish_make + .intercept(self.register_compiler_finish_make_taps.clone()); ctx .context .compiler_hooks @@ -121,6 +130,11 @@ impl rspack_core::Plugin for JsHooksAdapterPlugin { .compilation_hooks .execute_module .intercept(self.register_compilation_execute_module_taps.clone()); + ctx + .context + .compilation_hooks + .finish_modules + .intercept(self.register_compilation_finish_modules_taps.clone()); ctx .context .compilation_hooks @@ -330,40 +344,6 @@ impl rspack_core::Plugin for JsHooksAdapterPlugin { self.hooks.optimize_chunk_modules.call(compilation).await } - async fn finish_make( - &self, - compilation: &mut rspack_core::Compilation, - ) -> rspack_error::Result<()> { - if self.is_hook_disabled(&Hook::FinishMake) { - return Ok(()); - } - - // SAFETY: - // 1. `Compiler` is stored on the heap and pinned in binding crate. - // 2. `Compilation` outlives `JsCompilation` and `Compiler` outlives `Compilation`. - // 3. `JsCompilation` was replaced everytime a new `Compilation` was created before getting accessed. - let compilation = unsafe { JsCompilation::from_compilation(compilation) }; - - self.hooks.finish_make.call(compilation).await - } - - async fn finish_modules( - &self, - compilation: &mut rspack_core::Compilation, - ) -> rspack_error::Result<()> { - if self.is_hook_disabled(&Hook::FinishModules) { - return Ok(()); - } - - // SAFETY: - // 1. `Compiler` is stored on the heap and pinned in binding crate. - // 2. `Compilation` outlives `JsCompilation` and `Compiler` outlives `Compilation`. - // 3. `JsCompilation` was replaced everytime a new `Compilation` was created before getting accessed. - let compilation = unsafe { JsCompilation::from_compilation(compilation) }; - - self.hooks.finish_modules.call(compilation).await - } - async fn emit(&self, _: &mut rspack_core::Compilation) -> rspack_error::Result<()> { if self.is_hook_disabled(&Hook::Emit) { return Ok(()); @@ -407,6 +387,9 @@ impl JsHooksAdapterPlugin { register_compiler_make_taps: RegisterCompilerMakeTaps::new( register_js_taps.register_compiler_make_taps, ), + register_compiler_finish_make_taps: RegisterCompilerFinishMakeTaps::new( + register_js_taps.register_compiler_finish_make_taps, + ), register_compiler_should_emit_taps: RegisterCompilerShouldEmitTaps::new( register_js_taps.register_compiler_should_emit_taps, ), @@ -422,6 +405,9 @@ impl JsHooksAdapterPlugin { register_compilation_execute_module_taps: RegisterCompilationExecuteModuleTaps::new( register_js_taps.register_compilation_execute_module_taps, ), + register_compilation_finish_modules_taps: RegisterCompilationFinishModulesTaps::new( + register_js_taps.register_compilation_finish_modules_taps, + ), register_compilation_runtime_module_taps: RegisterCompilationRuntimeModuleTaps::new( register_js_taps.register_compilation_runtime_module_taps, ), diff --git a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs index 08df52e3f34..ac43b80cbac 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs @@ -305,7 +305,9 @@ impl BuiltinPlugin { BuiltinPluginName::FileUriPlugin => plugins.push(FileUriPlugin.boxed()), BuiltinPluginName::RuntimePlugin => plugins.push(RuntimePlugin.boxed()), BuiltinPluginName::JsonModulesPlugin => plugins.push(JsonPlugin.boxed()), - BuiltinPluginName::InferAsyncModulesPlugin => plugins.push(InferAsyncModulesPlugin.boxed()), + BuiltinPluginName::InferAsyncModulesPlugin => { + plugins.push(InferAsyncModulesPlugin::default().boxed()) + } BuiltinPluginName::JavascriptModulesPlugin => plugins.push(JsPlugin::default().boxed()), BuiltinPluginName::AsyncWebAssemblyModulesPlugin => { plugins.push(AsyncWasmPlugin::default().boxed()) diff --git a/crates/rspack_binding_values/src/hooks.rs b/crates/rspack_binding_values/src/hooks.rs index 865d2181b5a..34a12326703 100644 --- a/crates/rspack_binding_values/src/hooks.rs +++ b/crates/rspack_binding_values/src/hooks.rs @@ -24,10 +24,6 @@ pub struct JsHooks { pub optimize_tree: ThreadsafeFunction<(), ()>, #[napi(ts_type = "(compilation: JsCompilation) => void")] pub optimize_chunk_modules: ThreadsafeFunction, - #[napi(ts_type = "(compilation: JsCompilation) => void")] - pub finish_modules: ThreadsafeFunction, - #[napi(ts_type = "(compilation: JsCompilation) => void")] - pub finish_make: ThreadsafeFunction, #[napi( ts_type = "(data: AfterResolveData) => Promise<(boolean | void | AfterResolveCreateData)[]>" )] diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index 72f8edaf69a..43baeb41ae0 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -51,6 +51,7 @@ pub type CompilationStillValidModuleHook = AsyncSeriesHook; pub type CompilationSucceedModuleHook = AsyncSeriesHook; pub type CompilationExecuteModuleHook = SyncSeries4Hook; +pub type CompilationFinishModulesHook = AsyncSeriesHook; pub type CompilationRuntimeModuleHook = AsyncSeries3Hook; pub type CompilationChunkAssetHook = AsyncSeries2Hook; pub type CompilationProcessAssetsHook = AsyncSeriesHook; @@ -61,6 +62,7 @@ pub struct CompilationHooks { pub still_valid_module: CompilationStillValidModuleHook, pub succeed_module: CompilationSucceedModuleHook, pub execute_module: CompilationExecuteModuleHook, + pub finish_modules: CompilationFinishModulesHook, pub runtime_module: CompilationRuntimeModuleHook, pub chunk_asset: CompilationChunkAssetHook, pub process_assets: CompilationProcessAssetsHook, @@ -809,7 +811,11 @@ impl Compilation { pub async fn finish(&mut self, plugin_driver: SharedPluginDriver) -> Result<()> { let logger = self.get_logger("rspack.Compilation"); let start = logger.time("finish modules"); - plugin_driver.finish_modules(self).await?; + plugin_driver + .compilation_hooks + .finish_modules + .call(self) + .await?; logger.time_end(start); Ok(()) diff --git a/crates/rspack_core/src/compiler/mod.rs b/crates/rspack_core/src/compiler/mod.rs index fd3b2bce815..dcec7cdf085 100644 --- a/crates/rspack_core/src/compiler/mod.rs +++ b/crates/rspack_core/src/compiler/mod.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use rspack_error::Result; use rspack_fs::AsyncWritableFileSystem; use rspack_futures::FuturesResults; -use rspack_hook::{AsyncSeries2Hook, AsyncSeriesBailHook}; +use rspack_hook::{AsyncSeries2Hook, AsyncSeriesBailHook, AsyncSeriesHook}; use rspack_identifier::{IdentifierMap, IdentifierSet}; use rustc_hash::FxHashMap as HashMap; use swc_core::ecma::atoms::Atom; @@ -41,6 +41,7 @@ pub type CompilerThisCompilationHook = AsyncSeries2Hook; // should be AsyncParallelHook, but rspack need add MakeParam to incremental rebuild pub type CompilerMakeHook = AsyncSeries2Hook>; +pub type CompilerFinishMakeHook = AsyncSeriesHook; // should be SyncBailHook, but rspack need call js hook pub type CompilerShouldEmitHook = AsyncSeriesBailHook; @@ -49,6 +50,7 @@ pub struct CompilerHooks { pub this_compilation: CompilerThisCompilationHook, pub compilation: CompilerCompilationHook, pub make: CompilerMakeHook, + pub finish_make: CompilerFinishMakeHook, pub should_emit: CompilerShouldEmitHook, } @@ -181,7 +183,9 @@ where let start = logger.time("finish make hook"); self .plugin_driver - .finish_make(&mut self.compilation) + .compiler_hooks + .finish_make + .call(&mut self.compilation) .await?; logger.time_end(start); diff --git a/crates/rspack_core/src/plugin/api.rs b/crates/rspack_core/src/plugin/api.rs index 4eebb0a888e..5e88ce513bf 100644 --- a/crates/rspack_core/src/plugin/api.rs +++ b/crates/rspack_core/src/plugin/api.rs @@ -284,14 +284,6 @@ pub trait Plugin: Debug + Send + Sync { Ok(()) } - async fn finish_make(&self, _compilation: &mut Compilation) -> Result<()> { - Ok(()) - } - - async fn finish_modules(&self, _modules: &mut Compilation) -> Result<()> { - Ok(()) - } - /// Webpack resolves loaders in `NormalModuleFactory`, /// Rspack resolves it when normalizing configuration. /// So this hook is used to resolve inline loader (inline loader requests). diff --git a/crates/rspack_core/src/plugin/plugin_driver.rs b/crates/rspack_core/src/plugin/plugin_driver.rs index 6c4bba433a2..769557bdfd3 100644 --- a/crates/rspack_core/src/plugin/plugin_driver.rs +++ b/crates/rspack_core/src/plugin/plugin_driver.rs @@ -16,12 +16,11 @@ use crate::{ ModuleIdentifier, ModuleType, NormalModule, NormalModuleAfterResolveArgs, NormalModuleCreateData, NormalModuleFactoryHooks, OptimizeChunksArgs, Plugin, PluginAdditionalChunkRuntimeRequirementsOutput, PluginAdditionalModuleRequirementsOutput, - PluginBuildEndHookOutput, PluginChunkHashHookOutput, PluginCompilationHookOutput, PluginContext, - PluginFactorizeHookOutput, PluginJsChunkHashHookOutput, - PluginNormalModuleFactoryAfterResolveOutput, PluginNormalModuleFactoryBeforeResolveOutput, - PluginNormalModuleFactoryCreateModuleHookOutput, PluginNormalModuleFactoryModuleHookOutput, - PluginRenderChunkHookOutput, PluginRenderHookOutput, PluginRenderManifestHookOutput, - PluginRenderModuleContentOutput, PluginRenderStartupHookOutput, + PluginBuildEndHookOutput, PluginChunkHashHookOutput, PluginContext, PluginFactorizeHookOutput, + PluginJsChunkHashHookOutput, PluginNormalModuleFactoryAfterResolveOutput, + PluginNormalModuleFactoryBeforeResolveOutput, PluginNormalModuleFactoryCreateModuleHookOutput, + PluginNormalModuleFactoryModuleHookOutput, PluginRenderChunkHookOutput, PluginRenderHookOutput, + PluginRenderManifestHookOutput, PluginRenderModuleContentOutput, PluginRenderStartupHookOutput, PluginRuntimeRequirementsInTreeOutput, ProcessAssetsArgs, RenderArgs, RenderChunkArgs, RenderManifestArgs, RenderModuleContentArgs, RenderStartupArgs, Resolver, ResolverFactory, RuntimeRequirementsInTreeArgs, Stats, @@ -124,14 +123,6 @@ impl PluginDriver { Ok(()) } - pub async fn finish_make(&self, compilation: &mut Compilation) -> PluginCompilationHookOutput { - for plugin in &self.plugins { - plugin.finish_make(compilation).await?; - } - - Ok(()) - } - pub async fn content_hash(&self, args: &ContentHashArgs<'_>) -> Result { let mut result = HashMap::default(); for plugin in &self.plugins { @@ -490,14 +481,6 @@ impl PluginDriver { Ok(()) } - #[instrument(name = "plugin:finish_modules", skip_all)] - pub async fn finish_modules(&self, modules: &mut Compilation) -> Result<()> { - for plugin in &self.plugins { - plugin.finish_modules(modules).await?; - } - Ok(()) - } - pub async fn resolve_loader( &self, compiler_options: &CompilerOptions, diff --git a/crates/rspack_plugin_javascript/src/plugin/flag_dependency_exports_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/flag_dependency_exports_plugin.rs index c6fad4bb0ff..a499f864f6d 100644 --- a/crates/rspack_plugin_javascript/src/plugin/flag_dependency_exports_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/flag_dependency_exports_plugin.rs @@ -3,11 +3,13 @@ use std::collections::VecDeque; use itertools::Itertools; use rspack_core::{ - BuildMetaExportsType, Compilation, DependenciesBlock, DependencyId, ExportInfoProvided, - ExportNameOrSpec, ExportsInfoId, ExportsOfExportsSpec, ExportsSpec, ModuleGraph, - ModuleGraphConnection, ModuleIdentifier, MutableModuleGraph, Plugin, + ApplyContext, BuildMetaExportsType, Compilation, CompilerOptions, DependenciesBlock, + DependencyId, ExportInfoProvided, ExportNameOrSpec, ExportsInfoId, ExportsOfExportsSpec, + ExportsSpec, ModuleGraph, ModuleGraphConnection, ModuleIdentifier, MutableModuleGraph, Plugin, + PluginContext, }; use rspack_error::Result; +use rspack_hook::{plugin, plugin_hook, AsyncSeries}; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use swc_core::ecma::atoms::Atom; @@ -363,18 +365,33 @@ pub struct DefaultExportInfo<'a> { priority: Option, } +#[plugin] #[derive(Debug, Default)] pub struct FlagDependencyExportsPlugin; +#[plugin_hook(AsyncSeries for FlagDependencyExportsPlugin)] +async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { + let mut proxy = FlagDependencyExportsProxy::new(compilation.get_module_graph_mut()); + proxy.apply(); + Ok(()) +} + #[async_trait::async_trait] impl Plugin for FlagDependencyExportsPlugin { fn name(&self) -> &'static str { "FlagDependencyExportsPlugin" } - async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { - let mut proxy = FlagDependencyExportsProxy::new(compilation.get_module_graph_mut()); - proxy.apply(); + fn apply( + &self, + ctx: PluginContext<&mut ApplyContext>, + _options: &mut CompilerOptions, + ) -> Result<()> { + ctx + .context + .compilation_hooks + .finish_modules + .tap(finish_modules::new(self)); Ok(()) } } diff --git a/crates/rspack_plugin_javascript/src/plugin/infer_async_modules_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/infer_async_modules_plugin.rs index a1a8ef5383a..a18e45ff5cd 100644 --- a/crates/rspack_plugin_javascript/src/plugin/infer_async_modules_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/infer_async_modules_plugin.rs @@ -1,65 +1,83 @@ use std::collections::HashSet; use linked_hash_set::LinkedHashSet; -use rspack_core::{Compilation, DependencyType, Plugin}; +use rspack_core::{ + ApplyContext, Compilation, CompilerOptions, DependencyType, Plugin, PluginContext, +}; use rspack_error::Result; +use rspack_hook::{plugin, plugin_hook, AsyncSeries}; use rspack_identifier::Identifier; -#[derive(Debug)] +#[plugin] +#[derive(Debug, Default)] pub struct InferAsyncModulesPlugin; -#[async_trait::async_trait] -impl Plugin for InferAsyncModulesPlugin { - fn name(&self) -> &'static str { - "InferAsyncModulesPlugin" - } +#[plugin_hook(AsyncSeries for InferAsyncModulesPlugin)] +async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { + // fix: mut for-in + let mut queue = LinkedHashSet::new(); + let mut uniques = HashSet::new(); - async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { - // fix: mut for-in - let mut queue = LinkedHashSet::new(); - let mut uniques = HashSet::new(); + let mut modules: Vec = compilation + .get_module_graph() + .modules() + .values() + .filter(|m| { + if let Some(meta) = &m.build_meta() { + meta.has_top_level_await + } else { + false + } + }) + .map(|m| m.identifier()) + .collect(); - let mut modules: Vec = compilation - .get_module_graph() - .modules() - .values() - .filter(|m| { - if let Some(meta) = &m.build_meta() { - meta.has_top_level_await + modules.retain(|m| queue.insert(*m)); + + let module_graph = compilation.get_module_graph_mut(); + + while let Some(module) = queue.pop_front() { + module_graph.set_async(&module); + module_graph + .get_incoming_connections(&module) + .iter() + .filter(|con| { + if let Some(dep) = module_graph.dependency_by_id(&con.dependency_id) { + matches!( + dep.dependency_type(), + DependencyType::EsmImport(_) | DependencyType::EsmExport(_) + ) } else { false } }) - .map(|m| m.identifier()) - .collect(); - - modules.retain(|m| queue.insert(*m)); + .for_each(|con| { + if let Some(id) = &con.original_module_identifier { + if uniques.insert(*id) { + queue.insert(*id); + } + } + }); + } + Ok(()) +} - let module_graph = compilation.get_module_graph_mut(); +#[async_trait::async_trait] +impl Plugin for InferAsyncModulesPlugin { + fn name(&self) -> &'static str { + "InferAsyncModulesPlugin" + } - while let Some(module) = queue.pop_front() { - module_graph.set_async(&module); - module_graph - .get_incoming_connections(&module) - .iter() - .filter(|con| { - if let Some(dep) = module_graph.dependency_by_id(&con.dependency_id) { - matches!( - dep.dependency_type(), - DependencyType::EsmImport(_) | DependencyType::EsmExport(_) - ) - } else { - false - } - }) - .for_each(|con| { - if let Some(id) = &con.original_module_identifier { - if uniques.insert(*id) { - queue.insert(*id); - } - } - }); - } + fn apply( + &self, + ctx: PluginContext<&mut ApplyContext>, + _options: &mut CompilerOptions, + ) -> Result<()> { + ctx + .context + .compilation_hooks + .finish_modules + .tap(finish_modules::new(self)); Ok(()) } } diff --git a/crates/rspack_plugin_library/Cargo.toml b/crates/rspack_plugin_library/Cargo.toml index aee1735de6a..1a94e0962bf 100644 --- a/crates/rspack_plugin_library/Cargo.toml +++ b/crates/rspack_plugin_library/Cargo.toml @@ -12,5 +12,6 @@ once_cell = { workspace = true } regex = { workspace = true } rspack_core = { path = "../rspack_core" } rspack_error = { path = "../rspack_error" } +rspack_hook = { path = "../rspack_hook" } rspack_identifier = { path = "../rspack_identifier" } serde_json = { workspace = true } diff --git a/crates/rspack_plugin_library/src/assign_library_plugin.rs b/crates/rspack_plugin_library/src/assign_library_plugin.rs index f27293e14c8..e67faadb0d8 100644 --- a/crates/rspack_plugin_library/src/assign_library_plugin.rs +++ b/crates/rspack_plugin_library/src/assign_library_plugin.rs @@ -4,8 +4,8 @@ use once_cell::sync::Lazy; use regex::Regex; use rspack_core::tree_shaking::webpack_ext::ExportInfoExt; use rspack_core::{ - property_access, ChunkUkey, EntryData, LibraryExport, LibraryName, LibraryNonUmdObject, - UsageState, + property_access, ApplyContext, ChunkUkey, CompilerOptions, EntryData, LibraryExport, LibraryName, + LibraryNonUmdObject, UsageState, }; use rspack_core::{ rspack_sources::{ConcatSource, RawSource, SourceExt}, @@ -14,6 +14,7 @@ use rspack_core::{ PluginRenderStartupHookOutput, RenderArgs, RenderStartupArgs, SourceType, }; use rspack_error::{error, error_bail, Result}; +use rspack_hook::{plugin, plugin_hook, AsyncSeries}; use crate::utils::{get_options_for_chunk, COMMON_LIBRARY_NAME_MESSAGE}; @@ -72,6 +73,7 @@ struct AssignLibraryPluginParsed<'a> { export: Option<&'a LibraryExport>, } +#[plugin] #[derive(Debug)] pub struct AssignLibraryPlugin { options: AssignLibraryPluginOptions, @@ -79,7 +81,7 @@ pub struct AssignLibraryPlugin { impl AssignLibraryPlugin { pub fn new(options: AssignLibraryPluginOptions) -> Self { - Self { options } + Self::new_inner(options) } fn parse_options<'a>( @@ -164,11 +166,86 @@ impl AssignLibraryPlugin { } } +#[plugin_hook(AsyncSeries for AssignLibraryPlugin)] +async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { + let mut runtime_info = Vec::with_capacity(compilation.entries.len()); + for (entry_name, entry) in compilation.entries.iter() { + let EntryData { + dependencies, + options, + .. + } = entry; + let runtime = compilation.get_entry_runtime(entry_name, Some(options)); + let library_options = options + .library + .as_ref() + .or_else(|| compilation.options.output.library.as_ref()); + let module_of_last_dep = dependencies.last().and_then(|dep| { + compilation + .get_module_graph() + .get_module_by_dependency_id(dep) + }); + let Some(module_of_last_dep) = module_of_last_dep else { + continue; + }; + let Some(library_options) = library_options else { + continue; + }; + if let Some(export) = library_options + .export + .as_ref() + .and_then(|item| item.first()) + { + runtime_info.push(( + runtime, + Some(export.clone()), + module_of_last_dep.identifier(), + )); + } else { + runtime_info.push((runtime, None, module_of_last_dep.identifier())); + } + } + + for (runtime, export, module_identifier) in runtime_info { + if let Some(export) = export { + let exports_info = compilation + .get_module_graph_mut() + .get_export_info(module_identifier, &(export.as_str()).into()); + exports_info.set_used( + compilation.get_module_graph_mut(), + UsageState::Used, + Some(&runtime), + ); + } else { + let exports_info_id = compilation + .get_module_graph() + .get_exports_info(&module_identifier) + .id; + exports_info_id.set_used_in_unknown_way(compilation.get_module_graph_mut(), Some(&runtime)); + } + } + Ok(()) +} + #[async_trait::async_trait] impl Plugin for AssignLibraryPlugin { fn name(&self) -> &'static str { "rspack.AssignLibraryPlugin" } + + fn apply( + &self, + ctx: PluginContext<&mut ApplyContext>, + _options: &mut CompilerOptions, + ) -> Result<()> { + ctx + .context + .compilation_hooks + .finish_modules + .tap(finish_modules::new(self)); + Ok(()) + } + fn render(&self, _ctx: PluginContext, args: &RenderArgs) -> PluginRenderHookOutput { let Some(options) = self.get_options_for_chunk(args.compilation, args.chunk)? else { return Ok(None); @@ -189,66 +266,6 @@ impl Plugin for AssignLibraryPlugin { Ok(Some(args.source.clone())) } - async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { - let mut runtime_info = Vec::with_capacity(compilation.entries.len()); - for (entry_name, entry) in compilation.entries.iter() { - let EntryData { - dependencies, - options, - .. - } = entry; - let runtime = compilation.get_entry_runtime(entry_name, Some(options)); - let library_options = options - .library - .as_ref() - .or_else(|| compilation.options.output.library.as_ref()); - let module_of_last_dep = dependencies.last().and_then(|dep| { - compilation - .get_module_graph() - .get_module_by_dependency_id(dep) - }); - let Some(module_of_last_dep) = module_of_last_dep else { - continue; - }; - let Some(library_options) = library_options else { - continue; - }; - if let Some(export) = library_options - .export - .as_ref() - .and_then(|item| item.first()) - { - runtime_info.push(( - runtime, - Some(export.clone()), - module_of_last_dep.identifier(), - )); - } else { - runtime_info.push((runtime, None, module_of_last_dep.identifier())); - } - } - - for (runtime, export, module_identifier) in runtime_info { - if let Some(export) = export { - let exports_info = compilation - .get_module_graph_mut() - .get_export_info(module_identifier, &(export.as_str()).into()); - exports_info.set_used( - compilation.get_module_graph_mut(), - UsageState::Used, - Some(&runtime), - ); - } else { - let exports_info_id = compilation - .get_module_graph() - .get_exports_info(&module_identifier) - .id; - exports_info_id.set_used_in_unknown_way(compilation.get_module_graph_mut(), Some(&runtime)); - } - } - Ok(()) - } - fn render_startup( &self, _ctx: PluginContext, diff --git a/crates/rspack_plugin_library/src/export_property_library_plugin.rs b/crates/rspack_plugin_library/src/export_property_library_plugin.rs index d44a3c2122d..d556fadb286 100644 --- a/crates/rspack_plugin_library/src/export_property_library_plugin.rs +++ b/crates/rspack_plugin_library/src/export_property_library_plugin.rs @@ -3,11 +3,12 @@ use std::hash::Hash; use rspack_core::{ property_access, rspack_sources::{ConcatSource, RawSource, SourceExt}, - ChunkUkey, Compilation, EntryData, JsChunkHashArgs, LibraryExport, LibraryOptions, LibraryType, - Plugin, PluginContext, PluginJsChunkHashHookOutput, PluginRenderStartupHookOutput, - RenderStartupArgs, UsageState, + ApplyContext, ChunkUkey, Compilation, CompilerOptions, EntryData, JsChunkHashArgs, LibraryExport, + LibraryOptions, LibraryType, Plugin, PluginContext, PluginJsChunkHashHookOutput, + PluginRenderStartupHookOutput, RenderStartupArgs, UsageState, }; use rspack_error::Result; +use rspack_hook::{plugin, plugin_hook, AsyncSeries}; use crate::utils::get_options_for_chunk; @@ -16,6 +17,7 @@ struct ExportPropertyLibraryPluginParsed<'a> { export: Option<&'a LibraryExport>, } +#[plugin] #[derive(Debug, Default)] pub struct ExportPropertyLibraryPlugin { library_type: LibraryType, @@ -24,10 +26,7 @@ pub struct ExportPropertyLibraryPlugin { impl ExportPropertyLibraryPlugin { pub fn new(library_type: LibraryType, ns_object_used: bool) -> Self { - Self { - library_type, - ns_object_used, - } + Self::new_inner(library_type, ns_object_used) } fn parse_options<'a>( @@ -50,12 +49,95 @@ impl ExportPropertyLibraryPlugin { } } +#[plugin_hook(AsyncSeries for ExportPropertyLibraryPlugin)] +async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { + let mut runtime_info = Vec::with_capacity(compilation.entries.len()); + for (entry_name, entry) in compilation.entries.iter() { + let EntryData { + dependencies, + options, + .. + } = entry; + let runtime = compilation.get_entry_runtime(entry_name, Some(options)); + let library_options = options + .library + .as_ref() + .or_else(|| compilation.options.output.library.as_ref()); + let module_of_last_dep = dependencies.last().and_then(|dep| { + compilation + .get_module_graph() + .get_module_by_dependency_id(dep) + }); + let Some(module_of_last_dep) = module_of_last_dep else { + continue; + }; + let Some(library_options) = library_options else { + continue; + }; + if let Some(export) = library_options + .export + .as_ref() + .and_then(|item| item.first()) + { + runtime_info.push(( + runtime, + Some(export.clone()), + module_of_last_dep.identifier(), + )); + } else { + runtime_info.push((runtime, None, module_of_last_dep.identifier())); + } + } + + for (runtime, export, module_identifier) in runtime_info { + if let Some(export) = export { + let export_info_id = compilation + .get_module_graph_mut() + .get_export_info(module_identifier, &(export.as_str()).into()); + export_info_id.set_used( + compilation.get_module_graph_mut(), + UsageState::Used, + Some(&runtime), + ); + export_info_id + .get_export_info_mut(compilation.get_module_graph_mut()) + .can_mangle_use = Some(false); + } else { + let exports_info_id = compilation + .get_module_graph() + .get_exports_info(&module_identifier) + .id; + if self.ns_object_used { + exports_info_id.set_used_in_unknown_way(compilation.get_module_graph_mut(), Some(&runtime)); + } else { + exports_info_id + .set_all_known_exports_used(compilation.get_module_graph_mut(), Some(&runtime)); + } + } + } + + Ok(()) +} + #[async_trait::async_trait] impl Plugin for ExportPropertyLibraryPlugin { fn name(&self) -> &'static str { "rspack.ExportPropertyLibraryPlugin" } + fn apply( + &self, + ctx: PluginContext<&mut ApplyContext>, + _options: &mut CompilerOptions, + ) -> Result<()> { + ctx + .context + .compilation_hooks + .finish_modules + .tap(finish_modules::new(self)); + Ok(()) + } + fn render_startup( &self, _ctx: PluginContext, @@ -76,75 +158,6 @@ impl Plugin for ExportPropertyLibraryPlugin { Ok(Some(args.source.clone())) } - async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { - let mut runtime_info = Vec::with_capacity(compilation.entries.len()); - for (entry_name, entry) in compilation.entries.iter() { - let EntryData { - dependencies, - options, - .. - } = entry; - let runtime = compilation.get_entry_runtime(entry_name, Some(options)); - let library_options = options - .library - .as_ref() - .or_else(|| compilation.options.output.library.as_ref()); - let module_of_last_dep = dependencies.last().and_then(|dep| { - compilation - .get_module_graph() - .get_module_by_dependency_id(dep) - }); - let Some(module_of_last_dep) = module_of_last_dep else { - continue; - }; - let Some(library_options) = library_options else { - continue; - }; - if let Some(export) = library_options - .export - .as_ref() - .and_then(|item| item.first()) - { - runtime_info.push(( - runtime, - Some(export.clone()), - module_of_last_dep.identifier(), - )); - } else { - runtime_info.push((runtime, None, module_of_last_dep.identifier())); - } - } - - for (runtime, export, module_identifier) in runtime_info { - if let Some(export) = export { - let export_info_id = compilation - .get_module_graph_mut() - .get_export_info(module_identifier, &(export.as_str()).into()); - export_info_id.set_used( - compilation.get_module_graph_mut(), - UsageState::Used, - Some(&runtime), - ); - export_info_id - .get_export_info_mut(compilation.get_module_graph_mut()) - .can_mangle_use = Some(false); - } else { - let exports_info_id = compilation - .get_module_graph() - .get_exports_info(&module_identifier) - .id; - if self.ns_object_used { - exports_info_id - .set_used_in_unknown_way(compilation.get_module_graph_mut(), Some(&runtime)); - } else { - exports_info_id - .set_all_known_exports_used(compilation.get_module_graph_mut(), Some(&runtime)); - } - } - } - - Ok(()) - } fn js_chunk_hash( &self, _ctx: PluginContext, diff --git a/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs b/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs index 7b3acd512fc..7590367d483 100644 --- a/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs +++ b/crates/rspack_plugin_mf/src/sharing/provide_shared_plugin.rs @@ -9,7 +9,7 @@ use rspack_core::{ PluginNormalModuleFactoryModuleHookOutput, }; use rspack_error::{Diagnostic, Result}; -use rspack_hook::{plugin, plugin_hook, AsyncSeries2}; +use rspack_hook::{plugin, plugin_hook, AsyncSeries, AsyncSeries2}; use rspack_loader_runner::ResourceData; use rustc_hash::FxHashMap; use tokio::sync::RwLock; @@ -163,6 +163,31 @@ async fn compilation( Ok(()) } +#[plugin_hook(AsyncSeries for ProvideSharedPlugin)] +async fn finish_make(&self, compilation: &mut Compilation) -> Result<()> { + for (resource, config) in self.resolved_provide_map.read().await.iter() { + compilation + .add_include( + Box::new(ProvideSharedDependency::new( + config.share_scope.to_string(), + config.share_key.to_string(), + config.version.clone(), + resource.to_string(), + config.eager, + )), + EntryOptions { + name: None, + ..Default::default() + }, + ) + .await?; + } + self.resolved_provide_map.write().await.clear(); + self.match_provides.write().await.clear(); + self.prefix_match_provides.write().await.clear(); + Ok(()) +} + #[async_trait] impl Plugin for ProvideSharedPlugin { fn name(&self) -> &'static str { @@ -179,6 +204,11 @@ impl Plugin for ProvideSharedPlugin { .compiler_hooks .compilation .tap(compilation::new(self)); + ctx + .context + .compiler_hooks + .finish_make + .tap(finish_make::new(self)); Ok(()) } @@ -235,28 +265,4 @@ impl Plugin for ProvideSharedPlugin { } Ok(module) } - - async fn finish_make(&self, compilation: &mut Compilation) -> Result<()> { - for (resource, config) in self.resolved_provide_map.read().await.iter() { - compilation - .add_include( - Box::new(ProvideSharedDependency::new( - config.share_scope.to_string(), - config.share_key.to_string(), - config.version.clone(), - resource.to_string(), - config.eager, - )), - EntryOptions { - name: None, - ..Default::default() - }, - ) - .await?; - } - self.resolved_provide_map.write().await.clear(); - self.match_provides.write().await.clear(); - self.prefix_match_provides.write().await.clear(); - Ok(()) - } } diff --git a/crates/rspack_plugin_progress/src/lib.rs b/crates/rspack_plugin_progress/src/lib.rs index 1cb026eb933..ec67993d614 100644 --- a/crates/rspack_plugin_progress/src/lib.rs +++ b/crates/rspack_plugin_progress/src/lib.rs @@ -291,6 +291,23 @@ async fn succeed_module(&self, module: &mut BoxModule) -> Result<()> { Ok(()) } +#[plugin_hook(AsyncSeries for ProgressPlugin)] +async fn finish_make(&self, _compilation: &mut Compilation) -> Result<()> { + self.handler( + 0.69, + "building".to_string(), + vec!["finish make".to_string()], + None, + ); + Ok(()) +} + +#[plugin_hook(AsyncSeries for ProgressPlugin)] +async fn finish_modules(&self, _compilation: &mut Compilation) -> Result<()> { + self.sealing_hooks_report("finish modules", 0); + Ok(()) +} + #[plugin_hook(AsyncSeries for ProgressPlugin, stage = Compilation::PROCESS_ASSETS_STAGE_ADDITIONAL)] async fn process_assets(&self, _compilation: &mut Compilation) -> Result<()> { self.sealing_hooks_report("asset processing", 35); @@ -329,6 +346,16 @@ impl Plugin for ProgressPlugin { .compilation_hooks .succeed_module .tap(succeed_module::new(self)); + ctx + .context + .compiler_hooks + .finish_make + .tap(finish_make::new(self)); + ctx + .context + .compilation_hooks + .finish_modules + .tap(finish_modules::new(self)); ctx .context .compilation_hooks @@ -337,21 +364,6 @@ impl Plugin for ProgressPlugin { Ok(()) } - async fn finish_make(&self, _compilation: &mut Compilation) -> Result<()> { - self.handler( - 0.69, - "building".to_string(), - vec!["finish make".to_string()], - None, - ); - Ok(()) - } - - async fn finish_modules(&self, _modules: &mut Compilation) -> Result<()> { - self.sealing_hooks_report("finish modules", 0); - Ok(()) - } - fn seal(&self, _compilation: &mut Compilation) -> Result<()> { self.sealing_hooks_report("plugins", 1); Ok(()) diff --git a/crates/rspack_testing/src/test_config.rs b/crates/rspack_testing/src/test_config.rs index 40299ccd3fa..25a15869de2 100644 --- a/crates/rspack_testing/src/test_config.rs +++ b/crates/rspack_testing/src/test_config.rs @@ -557,7 +557,7 @@ impl TestConfig { plugins.push(rspack_plugin_warn_sensitive_module::WarnCaseSensitiveModulesPlugin.boxed()); - plugins.push(rspack_plugin_javascript::InferAsyncModulesPlugin {}.boxed()); + plugins.push(rspack_plugin_javascript::InferAsyncModulesPlugin::default().boxed()); if self.experiments.async_web_assembly { plugins.push(rspack_plugin_wasm::FetchCompileAsyncWasmPlugin {}.boxed()); plugins.push(rspack_plugin_wasm::AsyncWasmPlugin::default().boxed()); diff --git a/packages/rspack/src/Compilation.ts b/packages/rspack/src/Compilation.ts index 9ff5e1e07bc..c6d6f8036d5 100644 --- a/packages/rspack/src/Compilation.ts +++ b/packages/rspack/src/Compilation.ts @@ -116,7 +116,7 @@ export class Compilation { [Iterable, Iterable], void >; - finishModules: tapable.AsyncSeriesHook<[Iterable], void>; + finishModules: liteTapable.AsyncSeriesHook<[Iterable], void>; chunkAsset: liteTapable.SyncHook<[Chunk, string], void>; processWarnings: tapable.SyncWaterfallHook<[Error[]]>; succeedModule: liteTapable.SyncHook<[Module], void>; @@ -223,7 +223,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si "chunks", "modules" ]), - finishModules: new tapable.AsyncSeriesHook(["modules"]), + finishModules: new liteTapable.AsyncSeriesHook(["modules"]), chunkAsset: new liteTapable.SyncHook(["chunk", "filename"]), processWarnings: new tapable.SyncWaterfallHook(["warnings"]), succeedModule: new liteTapable.SyncHook(["module"]), diff --git a/packages/rspack/src/Compiler.ts b/packages/rspack/src/Compiler.ts index f18ae334362..1c84c2167ff 100644 --- a/packages/rspack/src/Compiler.ts +++ b/packages/rspack/src/Compiler.ts @@ -111,8 +111,7 @@ class Compiler { make: liteTapable.AsyncParallelHook<[Compilation]>; beforeCompile: tapable.AsyncSeriesHook<[CompilationParams]>; afterCompile: tapable.AsyncSeriesHook<[Compilation]>; - finishModules: tapable.AsyncSeriesHook<[any]>; - finishMake: tapable.AsyncSeriesHook<[Compilation]>; + finishMake: liteTapable.AsyncSeriesHook<[Compilation]>; entryOption: tapable.SyncBailHook<[string, EntryNormalized], any>; }; options: RspackOptionsNormalized; @@ -172,8 +171,7 @@ class Compiler { make: new liteTapable.AsyncParallelHook(["compilation"]), beforeCompile: new tapable.AsyncSeriesHook(["params"]), afterCompile: new tapable.AsyncSeriesHook(["compilation"]), - finishMake: new tapable.AsyncSeriesHook(["compilation"]), - finishModules: new tapable.AsyncSeriesHook(["modules"]), + finishMake: new liteTapable.AsyncSeriesHook(["compilation"]), entryOption: new tapable.SyncBailHook(["context", "entry"]) }; this.modifiedFiles = undefined; @@ -229,7 +227,6 @@ class Compiler { rawOptions, this.builtinPlugins, { - finishMake: this.#finishMake.bind(this), emit: this.#emit.bind(this), assetEmitted: this.#assetEmitted.bind(this), afterEmit: this.#afterEmit.bind(this), @@ -238,7 +235,6 @@ class Compiler { afterOptimizeModules: this.#afterOptimizeModules.bind(this), optimizeTree: this.#optimizeTree.bind(this), optimizeChunkModules: this.#optimizeChunkModules.bind(this), - finishModules: this.#finishModules.bind(this), normalModuleFactoryCreateModule: this.#normalModuleFactoryCreateModule.bind(this), normalModuleFactoryResolveForScheme: @@ -268,6 +264,10 @@ class Compiler { () => this.hooks.make, queried => async () => await queried.promise(this.compilation!) ), + registerCompilerFinishMakeTaps: this.#createRegisterTaps( + () => this.hooks.finishMake, + queried => async () => await queried.promise(this.compilation!) + ), registerCompilerShouldEmitTaps: this.#createRegisterTaps( () => this.hooks.shouldEmit, queried => () => queried.call(this.compilation!) @@ -376,6 +376,11 @@ class Compiler { this.#moduleExecutionResultsMap.set(id, executeResult); } ), + registerCompilationFinishModulesTaps: this.#createRegisterTaps( + () => this.compilation!.hooks.finishModules, + queried => async () => + await queried.promise(this.compilation!.modules) + ), registerCompilationChunkAssetTaps: this.#createRegisterTaps( () => this.compilation!.hooks.chunkAsset, queried => @@ -628,13 +633,11 @@ class Compiler { const disabledHooks: string[] = []; type HookMap = Record; const hookMap: HookMap = { - finishMake: this.hooks.finishMake, emit: this.hooks.emit, assetEmitted: this.hooks.assetEmitted, afterEmit: this.hooks.afterEmit, afterProcessAssets: this.compilation!.hooks.afterProcessAssets, optimizeTree: this.compilation!.hooks.optimizeTree, - finishModules: this.compilation!.hooks.finishModules, optimizeModules: this.compilation!.hooks.optimizeModules, afterOptimizeModules: this.compilation!.hooks.afterOptimizeModules, afterResolve: @@ -674,11 +677,6 @@ class Compiler { } } - async #finishMake() { - await this.hooks.finishMake.promise(this.compilation!); - this.#updateDisabledHooks(); - } - async #afterProcessAssets() { await this.compilation!.hooks.afterProcessAssets.promise( this.compilation!.assets @@ -784,13 +782,6 @@ class Compiler { this.#updateDisabledHooks(); } - async #finishModules() { - await this.compilation!.hooks.finishModules.promise( - this.compilation!.modules - ); - this.#updateDisabledHooks(); - } - async #emit() { await this.hooks.emit.promise(this.compilation!); this.#updateDisabledHooks();