第12章 unplugin-ast 使用指南
unplugin-ast
通过操作 AST 来转换你的代码。
安装
bash npm i unplugin-ast
Vite
ts // vite.config.ts import AST from 'unplugin-ast/vite'
export default defineConfig({ plugins: [AST()], })
Rollup
ts // rollup.config.js import AST from 'unplugin-ast/rollup'
export default { plugins: [AST()], }
Rolldown / tsdown
ts // rolldown.config.ts / tsdown.config.ts import AST from 'unplugin-ast/rolldown'
export default { plugins: [AST()], }
esbuild
ts import { build } from 'esbuild' import AST from 'unplugin-ast/esbuild'
build({ plugins: [AST()], })
Webpack
js // webpack.config.js import AST from 'unplugin-ast/webpack'
export default { /* ... */ plugins: [AST()], }
Rspack
ts // rspack.config.js import AST from 'unplugin-ast/rspack'
export default { /* ... */ plugins: [AST()], }
配置
以下是各配置项的默认值:
ts AST({ // 匹配需要转换的目标文件 include: [/\.[jt]sx?$/], exclude: undefined,
// Rollup 和 esbuild 不支持用 enforce 控制插件顺序,需要用户自行维护 enforce: undefined,
// https://yuku.fyi/parser/#options parserOptions: {},
// 参见下方"自定义 Transformer" transformer: [], })
Transformer
AST 节点遵循 ESTree / TypeScript-ESTree 规范。Yuku 提供的类型守卫、构建器、遍历器和工具函数都可以从 ast 命名空间导入,类型则直接从 unplugin-ast/yuku 导出,无需额外安装 Yuku 包。
ts import { ast, type CallExpression } from 'unplugin-ast/yuku'
内置 Transformer
RemoveWrapperFunction
ts import { RemoveWrapperFunction } from 'unplugin-ast/transformers'
/
* 移除包装函数,例如 `defineComponent`、`defineConfig`...
* @param functionNames - 要移除的函数名
*
* @example defineComponent()
* @example tw`text-red-500 ${expr}`
*/
export function RemoveWrapperFunction(
functionNames: Arrayable
转换前:
ts export default defineConfig(config)
转换后:
ts export default config
RemoveNode
ts import { RemoveNode } from 'unplugin-ast/transformers'
/
* 移除任意节点。
*/
export function RemoveNode(
onNode: (
node: Node,
parent: Node | null | undefined,
index: number | null | undefined,
) => Awaitable
自定义 Transformer
ts import type { Transformer } from 'unplugin-ast' import type { CallExpression } from 'unplugin-ast/yuku'
export const RemoveWrapperFunction = (
functionNames: string[],
): Transformer
transform(node) { return node.arguments[0] }, })
赞助者
许可证
MIT License © 2022-PRESENT 三咲智子