Babel.js 用TypeScript编写的巴别塔插件参数的类型是什么?

wd2eg0qa  于 2023-01-18  发布在  Babel
关注(0)|答案(2)|浏览(125)

我正在用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';

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

sqougxex

sqougxex1#

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

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

628mspwn

628mspwn2#

怎么样

import type * as Babel from '@babel/core';

export default function (babel: typeof Babel): Babel.PluginObj {
  // const t = babel.types;
  // const expression: Babel.Node = t.binaryExpression(...)
}

相关问题