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()],
}
esbuild
ts
// esbuild.config.js
import { build } from 'esbuild'
build({
plugins: [require('unplugin-ast/esbuild')()],
})
Webpack
ts
// webpack.config.js
module.exports = {
/* ... */
plugins: [require('unplugin-ast/webpack')()],
}
配置
以下是配置的默认值
ts
AST({
// 转换目标的过滤器
include: [/\.[jt]sx?$/],
exclude: undefined,
// Rollup 和 esbuild 不支持使用 enforce 来控制插件的顺序。用户需要手动维护顺序。
enforce: undefined,
// https://babeljs.io/docs/en/babel-parser#options
parserOptions: {},
// 请参阅下面的自定义转换器
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<string>,
): Transformer<CallExpression>
转换:
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<boolean>,
): Transformer
自定义转换器
ts
import type { CallExpression } from '@babel/types'
import type { Transformer } from 'unplugin-ast'
export const RemoveWrapperFunction = (
functionNames: string[],
): Transformer<CallExpression> => ({
onNode: (node) =>
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
functionNames.includes(node.callee.name),
transform(node) {
return node.arguments[0]
},
})