SWC Plugin

Tags
webrust
Created
Sep 6, 2024 6:01 AM

https://swc.rs/docs/plugin/ecmascript/cheatsheet

https://blog.sww.moe/post/swc-intro/

SWC 目前的依赖查找算法比较原始,只会去 node_modules 里面找文件,于是这套方案在 pnpm 和 yarn pnp 下面就会因为找不到目标文件而报错 // 导入 js 模块,用 js 查找路径

Fold 和 VisitMut:move 和 可变引用

  • VisitMut 以可变借用遍历节点,不需要返回值;
  • Fold 以转移所有权方式遍历节点,并将节点替换为返回值。

在实现 Visitor 时候,可以用下面几个宏定义来跳过 TypeScript 有关节点的遍历,来优化程序性能。

  • noop_fold_type!(); - 适用于 Fold

JsWord 和 String:在 AST 中使用 JsWord

标识符由两部分组成:(AtomSyntaxContext) // resolver 来标识 SyntaxContext,例如 #1 所有表达式都以 Box<T> 储存 改变导入语句:visit_mut_module_decl

插入node:先用 Vec<Stmt> 存起来,之后通过visit_mut_stmts or visit_mut_module_items 插入

文件名可能是 windows 路径,需要替换成 unix Path

添加前导注释: PluginCommentsProxy.add_leading(span.lo, comment); 由于所有权机制,删除一个 var 申明节点:

  • visit_mut_var_declarator 中 v.name.take() 标记
  • visit_mut_var_declarators 中过滤
  • visit_mut_stmt 中标记空语句
  • visit_mut_stmts 中过滤 // 可选,不过滤就有 “;”
  • visit_mut_module_items 中过滤 // 顶级变量储存在 `Vec<ModuleItem>` 中

在父处理器中删除节点:

  • visit_mut_stmt 中找到并 take() 标记节点
  • visit_mut_stmts 中过滤 // 可选,不过滤就有 “;”
  • visit_mut_module_items 中过滤 // 顶级变量储存在 `Vec<ModuleItem>` 中

Referencing parent node from handler of child node

This includes usage of paths and scope.

Caching some information about an AST node

You have two way to use informantion from a parent node. For first, you can precompute information from the parent node handler. Alternatively, you can clone the parent node and use it in the child node handler.

SuperMade with Super