第八章 - 编写 TypeScript 转换器

第八章 - 编写 TypeScript 转换器

学习如何重写AST来创建类似Babel的转换器

在上一章中,我们学习了如何使用TypeScript编译器API的工厂函数从零生成代码。本章将继续基于这个新知识,学习如何选择性地替换现有代码库中的部分内容!

这种选择性替换代码的策略被广泛应用于Babel、ESBuild、SWC等转译器和打包工具中。这些工具通常通过将代码转译为更多浏览器或Node引擎支持的语法,让开发者能更容易地编写现代JavaScript/TypeScript。

一个典型的降级转换例子是将箭头函数转为普通函数声明。曾经有段时间箭头函数刚被纳入ECMAScript规范,但浏览器还不支持该语法。许多开发者就使用工具转译代码,这样既能立即使用箭头函数编写代码,又能确保在浏览器中正常运行。

转换器实现

本章我们将实现把箭头函数转换为普通函数声明的例子。为了简化,我们不会递归查找所有箭头函数实例,只检查源文件中的根节点并进行转换。

我们继续使用fun.ts作为目标转换文件,内容如下:

typescript 复制代码
export const hello = (text?: string) => {  console.log(`Hello, ${text ?? "World!"}`)}
let world = <T>(t: T): T => {    return t  },  another = () => {    console.log("another")  },  a = 5,  b = "string",  c = true

这段代码展示了多种箭头函数:带export的const声明、使用泛型的函数、以及变量声明列表中的多个函数。我们的转换器需要处理所有这些情况。

在index.mjs中,我们先清空之前的内容,然后添加以下基础代码:

typescript 复制代码
import ts from "typescript"
const program = ts.createProgram(["fun.ts"], {
  module: ts.ModuleKind.ESNext
})

const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed })

for (const rootFileName of program.getRootFileNames()) {
  const sourceFile = program.getSourceFile(rootFileName)
  
  if (sourceFile && !sourceFile.isDeclarationFile) {
    transformSourceFile(sourceFile)
  }

  const str = printer.printNode(ts.EmitHint.Unspecified, sourceFile, sourceFile)
  console.log(str)
}

和之前一样,我们创建TypeScript程序来解析fun.ts,并用printer输出修改后的代码。遍历程序中的根文件时,如果不是声明文件就传给transformSourceFile函数处理。这个函数将包含我们的转换逻辑,处理完成后用printer打印结果。

现在来看transformSourceFile的实现。我们需要遍历源文件的根节点,如果发现变量声明语句且其初始化器是箭头函数,就执行转换:

typescript 复制代码
/**
 * @param {ts.SourceFile} sourceFile
 */
function transformSourceFile(sourceFile) {
  sourceFile.forEachChild((node) => {
    if (ts.isVariableStatement(node)) {
      node.declarationList.declarations.forEach((declaration) => {
        if (declaration.initializer && ts.isArrowFunction(declaration.initializer)) {
          declaration.initializer = transformArrowFunction(declaration.initializer)
        }
      })
    }
  })
}

找到箭头函数初始化器后,我们直接修改声明节点的初始化器,将其替换为新的函数表达式。转换工作由transformArrowFunction函数完成:

typescript 复制代码
/**
 * 将箭头函数转换为函数表达式
 * @param {ts.ArrowFunction} arrowFunction
 * @returns {ts.FunctionExpression}
 */
function transformArrowFunction(arrowFunction) {
  return ts.factory.createFunctionExpression(
    arrowFunction.modifiers,
    arrowFunction.asteriskToken,
    arrowFunction.name,
    arrowFunction.typeParameters,
    arrowFunction.parameters,
    arrowFunction.type,
    arrowFunction.body
  )
}

转换过程非常简单,因为箭头函数和普通函数共享大部分属性。我们只需将所有属性传递给新创建的节点,就能生成有效的AST。

运行脚本后,控制台将输出:

typescript 复制代码
export const hello = function (text?: string) {
  console.log(`Hello, ${text ?? "World!"}`)
}
let world = function <T>(t: T): T {
    return t
  },
  another = function () {
    console.log("another")
  },
  a = 5,
  b = "string",
  c = true

成功!所有根级箭头函数都替换成了函数表达式,且参数、类型、修饰符等所有信息都完整保留。如果需要,我们可以将这个输出字符串写入实际文件。

需要说明的是,当前实现只转换根节点。如果要转换文件中的所有箭头函数,需要像前几章那样递归遍历AST。

本章总结

本章我们通过将箭头函数转为普通函数的实例,学习了如何修改AST来自动重写代码。这是许多流行工具使用的强大功能,能为开发者提供更好的开发体验。

下一章我们将学习如何为转换逻辑编写单元测试,确保转换结果符合预期!

相关推荐
pan_junbiao3 小时前
Go 语言基本数据类型
java·前端·golang
ZhengEnCi10 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
kyriewen11 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
亲亲小宝宝鸭12 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生12 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水12 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
狗头大军之江苏分军13 小时前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬13 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月14 小时前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端
xurileidian14 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python