在 TypeScript 中编写的 Babel 插件参数的类型是什么? TypeScript 下 Babel 插件参数的数据类型是什么?

4

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

我在网上找到的一些例子都使用了这个,但这真的是它应该输入的方式吗?
2个回答

5
根据这个2019年的Babel开放问题,看起来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
}

在这个 Open Babel 问题修复之前,这将使代码更易读。


@babel/core 似乎没有提供类型。你是否添加了@types/babel-core - rschristian
@types/babel__core,我的意思是那些奇怪的包名。 - rschristian
从未尝试过这个 - 这些是这里唯一可用的类型吗?https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/customize-cra/src/babel.d.ts - Nicolas Bouvrette
不确定你为什么链接到 customize-cra - rschristian
我的错,这是Github上唯一显示的结果。我猜这是因为这个仓库太大了,但是是的,我看到babel-core 7.1有一个类型定义 - 如果你有想要发布的示例,它可能是一个有用的答案。 - Nicolas Bouvrette

0

怎么样?

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(...)
}

你的答案可以通过添加更多支持信息来改进。请[编辑]以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是否正确。你可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接