Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions crates/binding/src/js_hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ pub struct JsHooks {
pub generate_end: Option<JsFunction>,
#[napi(ts_type = "() => Promise<void>;")]
pub write_bundle: Option<JsFunction>,
#[napi(
ts_type = "(id: string, change: { event: 'create' | 'delete' | 'update' }) => Promise<void> | void;"
)]
pub watch_changes: Option<JsFunction>,
#[napi(ts_type = "(path: string, content: Buffer) => Promise<void>;")]
pub _on_generate_file: Option<JsFunction>,
#[napi(ts_type = "() => Promise<void>;")]
Expand All @@ -84,6 +88,7 @@ pub struct TsFnHooks {
pub generate_end: Option<ThreadsafeFunction<Value, ()>>,
pub load: Option<ThreadsafeFunction<String, Option<LoadResult>>>,
pub load_include: Option<ThreadsafeFunction<String, Option<bool>>>,
pub watch_changes: Option<ThreadsafeFunction<(String, WatchChangesParams), ()>>,
pub resolve_id:
Option<ThreadsafeFunction<(String, String, ResolveIdParams), Option<ResolveIdResult>>>,
pub _on_generate_file: Option<ThreadsafeFunction<WriteFile, ()>>,
Expand All @@ -106,6 +111,9 @@ impl TsFnHooks {
generate_end: hooks.generate_end.as_ref().map(|hook| unsafe {
ThreadsafeFunction::from_napi_value(env.raw(), hook.raw()).unwrap()
}),
watch_changes: hooks.watch_changes.as_ref().map(|hook| unsafe {
ThreadsafeFunction::from_napi_value(env.raw(), hook.raw()).unwrap()
}),
load: hooks.load.as_ref().map(|hook| unsafe {
ThreadsafeFunction::from_napi_value(env.raw(), hook.raw()).unwrap()
}),
Expand Down Expand Up @@ -142,6 +150,11 @@ pub struct LoadResult {
pub content_type: String,
}

#[napi(object, use_nullable = true)]
pub struct WatchChangesParams {
pub event: String,
}

#[napi(object, use_nullable = true)]
pub struct ResolveIdResult {
pub id: String,
Expand Down
15 changes: 14 additions & 1 deletion crates/binding/src/js_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use mako::plugin::{Plugin, PluginGenerateEndParams, PluginLoadParam, PluginResol
use mako::resolve::{ExternalResource, Resolution, ResolvedResource, ResolverResource};

use crate::js_hook::{
LoadResult, ResolveIdParams, ResolveIdResult, TransformResult, TsFnHooks, WriteFile,
LoadResult, ResolveIdParams, ResolveIdResult, TransformResult, TsFnHooks, WatchChangesParams,
WriteFile,
};

fn content_from_result(result: TransformResult) -> Result<Content> {
Expand Down Expand Up @@ -121,6 +122,18 @@ impl Plugin for JsPlugin {
Ok(())
}

fn watch_changes(&self, id: &str, event: &str, _context: &Arc<Context>) -> Result<()> {
if let Some(hook) = &self.hooks.watch_changes {
hook.call((
id.to_string(),
WatchChangesParams {
event: event.to_string(),
},
))?
}
Ok(())
}

fn write_bundle(&self, _context: &Arc<Context>) -> Result<()> {
if let Some(hook) = &self.hooks.write_bundle {
hook.call(())?
Expand Down
17 changes: 8 additions & 9 deletions crates/mako/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,12 +346,6 @@ impl DevServer {
"hot update chunks generated, next_full_hash: {:?}",
next_hash
);
// if !has_missing_deps {
// println!(
// "Hot rebuilt in {}",
// format!("{}ms", t_compiler.elapsed().as_millis()).bold()
// );
// }
if let Err(e) = next_hash {
eprintln!("Error in watch: {:?}", e);
return Err(e);
Expand Down Expand Up @@ -391,7 +385,6 @@ impl DevServer {
"Full rebuilt in {}",
format!("{}ms", t_compiler.elapsed().as_millis()).bold()
);

let params = PluginGenerateEndParams {
is_first_compile: false,
time: t_compiler.elapsed().as_millis() as i64,
Expand All @@ -401,12 +394,18 @@ impl DevServer {
.context
.plugin_driver
.generate_end(&params, &compiler.context)
.unwrap();
.map_err(|e| {
debug!("generate end failed: {:?}", e);
e
})?;
compiler
.context
.plugin_driver
.write_bundle(&compiler.context)
.unwrap();
.map_err(|e| {
debug!("write bundle failed: {:?}", e);
e
})?;
}

let receiver_count = txws.receiver_count();
Expand Down
15 changes: 15 additions & 0 deletions crates/mako/src/dev/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,27 @@ impl Compiler {
for (path, update_type) in paths {
match update_type {
UpdateType::Add => {
self.context.plugin_driver.watch_changes(
&path.to_string_lossy(),
"create",
&self.context,
)?;
Comment on lines +189 to +193
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

建议提取重复代码,减少冗余

在不同的 UpdateType 分支中,对 self.context.plugin_driver.watch_changes 的调用几乎相同,除了第二个参数不同("create"、"delete"、"update")。可以考虑将这些调用抽取出来,减少代码重复,提高代码的可读性和维护性。

可考虑如下修改:

     match update_type {
-        UpdateType::Add => {
-            self.context.plugin_driver.watch_changes(
-                &path.to_string_lossy(),
-                "create",
-                &self.context,
-            )?;
-            added.push(path);
-        }
-        UpdateType::Remove => {
-            self.context.plugin_driver.watch_changes(
-                &path.to_string_lossy(),
-                "delete",
-                &self.context,
-            )?;
-            removed.push(path);
-        }
-        UpdateType::Modify => {
-            self.context.plugin_driver.watch_changes(
-                &path.to_string_lossy(),
-                "update",
-                &self.context,
-            )?;
-            modified.push(path);
-        }
+        UpdateType::Add => ("create", &mut added),
+        UpdateType::Remove => ("delete", &mut removed),
+        UpdateType::Modify => ("update", &mut modified),
     };
+    self.context.plugin_driver.watch_changes(
+        &path.to_string_lossy(),
+        change_type,
+        &self.context,
+    )?;
+    vec_to_push.push(path);

这样可以减少重复的代码。

Also applies to: 197-201, 205-209

added.push(path);
}
UpdateType::Remove => {
self.context.plugin_driver.watch_changes(
&path.to_string_lossy(),
"delete",
&self.context,
)?;
removed.push(path);
}
UpdateType::Modify => {
self.context.plugin_driver.watch_changes(
&path.to_string_lossy(),
"update",
&self.context,
)?;
modified.push(path);
}
}
Expand Down
11 changes: 11 additions & 0 deletions crates/mako/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ pub trait Plugin: Any + Send + Sync {
Ok(())
}

fn watch_changes(&self, _id: &str, _event: &str, _context: &Arc<Context>) -> Result<()> {
Ok(())
}

fn runtime_plugins(&self, _context: &Arc<Context>) -> Result<Vec<String>> {
Ok(Vec::new())
}
Expand Down Expand Up @@ -335,6 +339,13 @@ impl PluginDriver {
Ok(())
}

pub fn watch_changes(&self, id: &str, event: &str, context: &Arc<Context>) -> Result<()> {
for plugin in &self.plugins {
plugin.watch_changes(id, event, context)?;
}
Ok(())
}

pub fn generate_begin(&self, context: &Arc<Context>) -> Result<()> {
for plugin in &self.plugins {
plugin.generate_begin(context)?;
Expand Down
1 change: 1 addition & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,7 @@ Specify the plugins to use.
};
}) => void;
writeBundle?: () => void;
watchChanges?: (id: string, params: { event: "create" | "delete" | "update" }) => void;
load?: (filePath: string) => Promise<{ content: string, type: 'css'|'js'|'jsx'|'ts'|'tsx' }>;
loadInclude?: (filePath: string) => boolean;
resolveId?: (id: string, importer: string, { isEntry: bool }) => Promise<{ id: string, external: bool }>;
Expand Down
1 change: 1 addition & 0 deletions docs/config.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,7 @@ import(/* webpackIgnore: true */ "./foo");
};
}) => void;
writeBundle?: () => void;
watchChanges?: (id: string, params: { event: "create" | "delete" | "update" }) => void;
load?: (filePath: string) => Promise<{ content: string, type: 'css'|'js'|'jsx'|'ts'|'tsx' }>;
loadInclude?: (filePath: string) => boolean;
resolveId?: (id: string, importer: string, { isEntry: bool }) => Promise<{ id: string, external: bool }>;
Expand Down
7 changes: 7 additions & 0 deletions packages/mako/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ export interface JsHooks {
};
}) => void;
writeBundle?: () => Promise<void>;
watchChanges?: (
id: string,
change: { event: 'create' | 'delete' | 'update' },
) => Promise<void> | void;
onGenerateFile?: (path: string, content: Buffer) => Promise<void>;
buildStart?: () => Promise<void>;
buildEnd?: () => Promise<void>;
Expand All @@ -74,6 +78,9 @@ export interface LoadResult {
content: string;
type: string;
}
export interface WatchChangesParams {
event: string;
}
export interface ResolveIdResult {
id: string;
external: boolean | null;
Expand Down