
许多开发者在探索swc的插件系统时,常常会疑惑是否可以使用javascript或typescript编写插件,类似于babel的插件生态。尽管目前swc官方文档主要提及rust编写的插件,且成熟的js/ts插件api仍在演进中,但这并不意味着无法使用javascript/typescript对代码进行高级转换。
SWC的核心能力之一是其高效的解析和转换能力。它能够将源代码解析成抽象语法树(AST),并能将修改后的AST重新生成为代码。这个过程提供了一个关键的接口:在源代码被解析成AST之后,但在AST被转换回代码之前,开发者可以对AST进行任意的修改。这种AST层面的数据操作,实际上就是实现自定义“插件逻辑”的有效途径。
SWC提供@swc/core库,其中包含parse和transform两个核心API:
因此,实现自定义代码转换的流程如下:
以下示例演示了如何使用@swc/core库,在AST层面修改代码中的导入路径,将所有.ts、.mts和.cts后缀的导入语句改为.js后缀。
立即学习“Java免费学习笔记(深入)”;
import swc from '@swc/core';
// 待转换的源代码
let source = `
import abc from './abc.ts'
import def from "./def.mts"
import('./ghi.cts')
const foo = require('./bar.ts')
`;
async function transformImports(code: string) {
// 1. 解析源代码为AST
let program = await swc.parse(code, {
syntax: 'typescript', // 指定源代码语法为TypeScript
comments: false, // 不保留注释
script: true, // 视为脚本文件
target: 'esnext', // 目标ES版本
});
// 2. 实现自定义的插件逻辑:遍历并修改AST
// AST的根节点是Program,其body属性包含了顶层语句数组
for (let item of program.body) {
switch (item.type) {
// 处理 ImportDeclaration 类型的节点(如 import abc from './abc.ts')
case 'ImportDeclaration':
// 导入声明的source属性包含导入路径的字面量信息
// raw属性是原始的字符串表示,如 "'./abc.ts'"
if (item.source && item.source.raw) {
item.source.raw = item.source.raw
.replace('.ts"', '.js"')
.replace('.mts"', '.js"')
.replace('.cts"', '.js"');
}
break;
// 处理 ExpressionStatement 类型的节点,例如动态导入 import('./ghi.cts')
case 'ExpressionStatement':
// 检查表达式是否为 CallExpression (函数调用)
if (item.expression.type === 'CallExpression') {
const callExpr = item.expression;
// 检查调用的callee是否为Import (动态导入)
if (callExpr.callee.type === 'Import') {
// 动态导入的参数是数组,通常第一个参数是导入路径
if (callExpr.arguments.length > 0 && callExpr.arguments[0].expression.type === 'StringLiteral') {
const arg = callExpr.arguments[0].expression;
arg.raw = arg.raw
.replace('.ts"', '.js"')
.replace('.mts"', '.js"')
.replace('.cts"', '.js"');
}
}
}
break;
// 针对 CommonJS require() 的处理(虽然SWC主要用于ESM,但也可处理)
case 'VariableDeclaration':
for (const declarator of item.declarations) {
if (declarator.init && declarator.init.type === 'CallExpression' &&
declarator.init.callee.type === 'Identifier' && declarator.init.callee.value === 'require') {
if (declarator.init.arguments.length > 0 && declarator.init.arguments[0].expression.type === 'StringLiteral') {
const arg = declarator.init.arguments[0].expression;
arg.raw = arg.raw
.replace('.ts"', '.js"')
.replace('.mts"', '.js"')
.replace('.cts"', '.js"');
}
}
}
break;
default:
// 打印其他类型的节点,以便了解AST结构
// console.log(`Unhandled node type: ${item.type}`);
}
}
// 3. 将修改后的AST转换回代码
const transformedCode = await swc.transform(program, {
jsc: {
target: 'esnext', // 目标ES版本
// minify: {
// // 注意:SWC的minify功能在某些版本可能存在已知问题,
// // 使用时请谨慎测试或避免在此阶段使用
// // compress: {},
// mangle: {},
// },
},
});
return transformedCode.code;
}
// 执行转换并打印结果
transformImports(source).then(result => {
console.log('--- Original Code ---');
console.log(source);
console.log('\n--- Transformed Code ---');
console.log(result);
}).catch(error => {
console.error('Transformation failed:', error);
});代码解析:
通过上述基于AST的操作,即使没有直接的JavaScript/TypeScript插件API,开发者仍然能够利用SWC强大的解析和转换能力,实现高度定制化的代码转换需求。这种方法提供了极大的灵活性,使得JavaScript/TypeScript开发者也能充分利用SWC在构建工具链中的优势。
以上就是SWC中基于JavaScript/TypeScript的AST操作实现代码转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号