【问题标题】:What is the type of a Babel plugin parameter written in TypeScript?用 TypeScript 编写的 Babel 插件参数的类型是什么?
【发布时间】:2021-09-26 05:41:06
【问题描述】:

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

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

【问题讨论】:

    标签: typescript babeljs typescript-typings babel-plugin


    【解决方案1】:

    根据这个从 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 问题得到修复。

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 2021-01-09
      • 2018-03-09
      • 1970-01-01
      • 2012-10-24
      • 2016-06-28
      • 2015-11-16
      • 2021-07-06
      • 2016-08-16
      相关资源
      最近更新 更多