Skip to content

Commit

Permalink
feat(swc-plugin-canyon): update
Browse files Browse the repository at this point in the history
  • Loading branch information
Allen Zhang (张涛) committed Oct 19, 2024
1 parent 68a3f73 commit d7edc75
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
2 changes: 1 addition & 1 deletion plugins/swc-plugin-canyon/package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
35 changes: 31 additions & 4 deletions plugins/swc-plugin-canyon/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<String>`
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
}
}

0 comments on commit d7edc75

Please sign in to comment.