Skip to content

Commit

Permalink
feat: add finishMake hook
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitry-stepanenko committed Jun 2, 2023
1 parent 2b5e67e commit 6a25e1e
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 4 deletions.
6 changes: 2 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"**/.DS_Store": true,
"**/*.bk": true,
"/target": true,
"**/.yarn": true,
"**/.yarn": true
},
"[typescript]": {
"editor.formatOnSave": true
Expand All @@ -19,9 +19,7 @@
"cSpell.caseSensitive": true,
"json.schemas": [
{
"fileMatch": [
"test.config.json"
],
"fileMatch": ["test.config.json"],
// Point to the options schema of rspack.
"url": "./crates/rspack_testing/test.config.scheme.json"
}
Expand Down
1 change: 1 addition & 0 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ export interface JsHooks {
beforeCompile: (...args: any[]) => any
afterCompile: (...args: any[]) => any
finishModules: (...args: any[]) => any
finishMake: (...args: any[]) => any
beforeResolve: (...args: any[]) => any
afterResolve: (...args: any[]) => any
contextModuleBeforeResolve: (...args: any[]) => any
Expand Down
2 changes: 2 additions & 0 deletions crates/node_binding/src/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::sync::{Arc, RwLock};
#[derive(PartialEq)]
pub enum Hook {
Make,
FinishMake,
Compilation,
ThisCompilation,
ProcessAssetsStageAdditional,
Expand Down Expand Up @@ -33,6 +34,7 @@ impl From<String> for Hook {
fn from(s: String) -> Self {
match s.as_str() {
"make" => Hook::Make,
"finishMake" => Hook::FinishMake,
"compilation" => Hook::Compilation,
"thisCompilation" => Hook::ThisCompilation,
"processAssetsStageAdditional" => Hook::ProcessAssetsStageAdditional,
Expand Down
1 change: 1 addition & 0 deletions crates/node_binding/src/js_values/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub struct JsHooks {
pub before_compile: JsFunction,
pub after_compile: JsFunction,
pub finish_modules: JsFunction,
pub finish_make: JsFunction,
pub before_resolve: JsFunction,
pub after_resolve: JsFunction,
pub context_module_before_resolve: JsFunction,
Expand Down
27 changes: 27 additions & 0 deletions crates/node_binding/src/plugins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pub struct JsHooksAdapter {
pub before_compile_tsfn: ThreadsafeFunction<(), ()>,
pub after_compile_tsfn: ThreadsafeFunction<JsCompilation, ()>,
pub finish_modules_tsfn: ThreadsafeFunction<JsCompilation, ()>,
pub finish_make_tsfn: ThreadsafeFunction<JsCompilation, ()>,
pub chunk_asset_tsfn: ThreadsafeFunction<JsChunkAssetArgs, ()>,
pub before_resolve: ThreadsafeFunction<BeforeResolveData, (Option<bool>, BeforeResolveData)>,
pub after_resolve: ThreadsafeFunction<AfterResolveData, Option<bool>>,
Expand Down Expand Up @@ -439,6 +440,28 @@ impl rspack_core::Plugin for JsHooksAdapter {
.map_err(|err| internal_error!("Failed to call after compile: {err}"))?
}

async fn finish_make(
&mut self,
compilation: &mut rspack_core::Compilation,
) -> rspack_error::Result<()> {
if self.is_hook_disabled(&Hook::FinishMake) {
return Ok(());
}

let compilation = JsCompilation::from_compilation(unsafe {
std::mem::transmute::<&'_ mut rspack_core::Compilation, &'static mut rspack_core::Compilation>(
compilation,
)
});

self
.finish_make_tsfn
.call(compilation, ThreadsafeFunctionCallMode::NonBlocking)
.into_rspack_result()?
.await
.map_err(|err| internal_error!("Failed to call finish make: {err}"))?
}

async fn finish_modules(
&mut self,
compilation: &mut rspack_core::Compilation,
Expand Down Expand Up @@ -528,6 +551,7 @@ impl JsHooksAdapter {
before_compile,
after_compile,
finish_modules,
finish_make,
chunk_asset,
} = js_hooks;

Expand Down Expand Up @@ -564,6 +588,8 @@ impl JsHooksAdapter {
js_fn_into_theadsafe_fn!(before_compile, env);
let after_compile_tsfn: ThreadsafeFunction<JsCompilation, ()> =
js_fn_into_theadsafe_fn!(after_compile, env);
let finish_make_tsfn: ThreadsafeFunction<JsCompilation, ()> =
js_fn_into_theadsafe_fn!(finish_make, env);
let finish_modules_tsfn: ThreadsafeFunction<JsCompilation, ()> =
js_fn_into_theadsafe_fn!(finish_modules, env);
let context_module_before_resolve: ThreadsafeFunction<BeforeResolveData, Option<bool>> =
Expand Down Expand Up @@ -603,6 +629,7 @@ impl JsHooksAdapter {
context_module_before_resolve,
normal_module_factory_resolve_for_scheme,
finish_modules_tsfn,
finish_make_tsfn,
chunk_asset_tsfn,
after_resolve,
})
Expand Down
8 changes: 8 additions & 0 deletions crates/rspack_core/src/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,14 @@ where
async fn compile(&mut self, params: SetupMakeParam) -> Result<()> {
let option = self.options.clone();
self.compilation.make(params).await?;

self
.plugin_driver
.write()
.await
.finish_make(&mut self.compilation)
.await?;

self.compilation.finish(self.plugin_driver.clone()).await?;
// by default include all module in final chunk
self.compilation.include_module_ids = self
Expand Down
4 changes: 4 additions & 0 deletions crates/rspack_core/src/plugin/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,10 @@ pub trait Plugin: Debug + Send + Sync {
Ok(())
}

async fn finish_make(&mut self, _compilation: &mut Compilation) -> Result<()> {
Ok(())
}

async fn finish_modules(&mut self, _modules: &mut Compilation) -> Result<()> {
Ok(())
}
Expand Down
11 changes: 11 additions & 0 deletions crates/rspack_core/src/plugin/plugin_driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,17 @@ impl PluginDriver {

Ok(())
}

pub async fn finish_make(
&mut self,
compilation: &mut Compilation,
) -> PluginCompilationHookOutput {
for plugin in &mut self.plugins {
plugin.finish_make(compilation).await?;
}

Ok(())
}
/// Executed while initializing the compilation, right before emitting the compilation event. This hook is not copied to child compilers.
///
/// See: https://webpack.js.org/api/compiler-hooks/#thiscompilation
Expand Down
9 changes: 9 additions & 0 deletions packages/rspack/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ class Compiler {
beforeCompile: tapable.AsyncSeriesHook<any>;
afterCompile: tapable.AsyncSeriesHook<[Compilation]>;
finishModules: tapable.AsyncSeriesHook<[any]>;
finishMake: tapable.AsyncSeriesHook<[Compilation]>;
};
options: RspackOptionsNormalized;
#disabledHooks: string[];
Expand Down Expand Up @@ -234,6 +235,7 @@ class Compiler {
make: new tapable.AsyncParallelHook(["compilation"]),
beforeCompile: new tapable.AsyncSeriesHook(["params"]),
afterCompile: new tapable.AsyncSeriesHook(["compilation"]),
finishMake: new tapable.AsyncSeriesHook(["compilation"]),
finishModules: new tapable.AsyncSeriesHook(["modules"])
};
this.modifiedFiles = undefined;
Expand Down Expand Up @@ -284,6 +286,7 @@ class Compiler {
{
beforeCompile: this.#beforeCompile.bind(this),
afterCompile: this.#afterCompile.bind(this),
finishMake: this.#finishMake.bind(this),
make: this.#make.bind(this),
emit: this.#emit.bind(this),
assetEmitted: this.#assetEmitted.bind(this),
Expand Down Expand Up @@ -565,6 +568,7 @@ class Compiler {
make: this.hooks.make,
beforeCompile: this.hooks.beforeCompile,
afterCompile: this.hooks.afterCompile,
finishMake: this.hooks.finishMake,
emit: this.hooks.emit,
assetEmitted: this.hooks.assetEmitted,
afterEmit: this.hooks.afterEmit,
Expand Down Expand Up @@ -624,6 +628,11 @@ class Compiler {
this.#updateDisabledHooks();
}

async #finishMake() {
await this.hooks.finishMake.promise(this.compilation);
this.#updateDisabledHooks();
}

async #processAssets(stage: number) {
await this.compilation
.__internal_getProcessAssetsHookByStage(stage)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const a = 3;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { a } from "./a.js";

it("should compile successfully", () => {
expect(a).toBe(3);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const { deepEqual, strict } = require("assert");
const pluginName = "plugin";

class Plugin {
apply(compiler) {
let order = [];

compiler.hooks.beforeCompile.tap(pluginName, () => {
order.push("hooks.beforeCompile");
});
compiler.hooks.make.tap(pluginName, () => {
order.push("hooks.make");
});
compiler.hooks.finishMake.tap(pluginName, () => {
order.push("hooks.finishMake");
});
compiler.hooks.afterCompile.tap(pluginName, () => {
order.push("hooks.afterCompile");
});

compiler.hooks.done.tap(pluginName, stats => {
let json = stats.toJson();
strict(json.errors.length === 0, `${json.errors}`);
deepEqual(order, [
"hooks.beforeCompile",
"hooks.make",
"hooks.finishMake",
"hooks.afterCompile"
]);
});
}
}

/**@type {import('@rspack/cli').Configuration}*/
module.exports = {
context: __dirname,
module: {
rules: []
},
plugins: [new Plugin()]
};

0 comments on commit 6a25e1e

Please sign in to comment.