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

What is the type of a Babel plugin parameter written in TypeScript?

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

export default function myPlugin({ types: t }: typeof babel): PluginObj {

我从中得到了一些类型:

import type { PluginObj, PluginPass } from '@babel/core';

困扰我的部分是来自

{ types: t }: typeof babel
import type * as babel from '@babel/core';

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

根据这个 2019 年开放的 Babel issue,看起来 Babel 的类型分为 '@babel/core@babel/types。有一点不要混淆,与 Node 的其他一些“类型”包不同,@babel/types 不是 Babel 的“类型”包,而是包含用于手动构建 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
}

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