用 TypeScript 编写的 Babel 插件参数的类型是什么?

Nic*_*tte 4 typescript babeljs typescript-typings babel-plugin

我正在用 TypeScript 编写 Babel 插件,并且一直在努力寻找大量这样做的示例或文档。例如,我正在编写一个具有以下签名的访问者插件:

export default function myPlugin({ types: t }: typeof babel): PluginObj {
Run Code Online (Sandbox Code Playgroud)

我从以下地方得到几种类型:

import type { PluginObj, PluginPass } from '@babel/core';
Run Code Online (Sandbox Code Playgroud)

令我困扰的部分是{ types: t }: typeof babel来自

import type * as babel from '@babel/core';
Run Code Online (Sandbox Code Playgroud)

我在网上找到的几个例子都使用了这个,但这真的是它应该如何输入的吗?

Nic*_*tte 5

根据 2019 年公开的 Babel问题,Babel 的类型似乎分为'@babel/core@babel/types。有一点不要混淆,与 Node 的其他一些“类型”包不同,@babel/typesBabel 不是“类型”包,而是包含手动构建 AST 和检查 AST 节点类型的方法。所以它们基本上是具有不同目标的不同包。

Babel 包的挑战在于它们似乎使用命名空间(通配符)导入,并且包本身似乎没有任何类型。

解决此问题的一种快速方法:

import type * as BabelCoreNamespace from '@babel/core';
import type * as BabelTypesNamespace from '@babel/types';
import type { PluginObj } from '@babel/core';

export type Babel = typeof BabelCoreNamespace;
export type BabelTypes = typeof BabelTypesNamespace;

export default function myPlugin(babel: Babel): PluginObj {
    // Some plugin code here
}

Run Code Online (Sandbox Code Playgroud)

这使得代码更具可读性,直到解决这个开放的 Babel 问题。