From d7edc758f0a388a7d70a87d7453943dec4882e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Allen=20Zhang=20=28=E5=BC=A0=E6=B6=9B=29?= Date: Sat, 19 Oct 2024 22:20:40 +0800 Subject: [PATCH] feat(swc-plugin-canyon): update --- plugins/swc-plugin-canyon/package.json | 2 +- plugins/swc-plugin-canyon/src/lib.rs | 35 +++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/plugins/swc-plugin-canyon/package.json b/plugins/swc-plugin-canyon/package.json index 2ca0317e..138c6d0e 100644 --- a/plugins/swc-plugin-canyon/package.json +++ b/plugins/swc-plugin-canyon/package.json @@ -1,6 +1,6 @@ { "name": "swc-plugin-canyon", - "version": "0.0.2-alpha.3", + "version": "0.0.2-alpha.5", "description": "Canyon SWC plugin, for debugging", "main": "swc_plugin_canyon.wasm", "scripts": { diff --git a/plugins/swc-plugin-canyon/src/lib.rs b/plugins/swc-plugin-canyon/src/lib.rs index 1139296d..0bfb594d 100644 --- a/plugins/swc-plugin-canyon/src/lib.rs +++ b/plugins/swc-plugin-canyon/src/lib.rs @@ -1,17 +1,44 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] use swc_core::plugin::proxies::TransformPluginProgramMetadata; -use swc_ecma_ast::Program; +use swc_ecma_ast::{Program, Module, ModuleItem, Script}; +use swc_ecma_visit::{Fold, FoldWith}; use swc_plugin_macro::plugin_transform; +use swc_core::ecma::utils::quote_str; #[plugin_transform] fn plugin(program: Program, metadata: TransformPluginProgramMetadata) -> Program { - // 需要提供 `TransformPluginMetadataContextKind` 参数给 `get_context` 方法 + // 打印文件路径 if let Some(context) = metadata.get_context(&swc_core::plugin::metadata::TransformPluginMetadataContextKind::Filename) { - // 处理返回的 `Option` println!("当前文件的路径: {}", context); } else { println!("无法获取文件路径"); } - program + + // 直接在每个文件末尾插入指定的代码 + program.fold_with(&mut AddSimpleCode) +} + +struct AddSimpleCode; + +impl Fold for AddSimpleCode { + fn fold_module(&mut self, mut module: Module) -> Module { + let new_code = "(new Function('this')).__canyon__={tizhong:\"123\"};"; + let new_item = ModuleItem::Stmt(swc_ecma_ast::Stmt::Expr(swc_ecma_ast::ExprStmt { + expr: Box::new(swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(quote_str(new_code)))), + span: Default::default(), + })); + module.body.push(new_item); + module + } + + fn fold_script(&mut self, mut script: Script) -> Script { + let new_code = "(new Function('this')).__canyon__={tizhong:\"123\"};"; + let new_item = swc_ecma_ast::Stmt::Expr(swc_ecma_ast::ExprStmt { + expr: Box::new(swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(quote_str(new_code)))), + span: Default::default(), + }); + script.body.push(new_item); + script + } }