簡體   English   中英

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問題,看起來 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 問題得到修復。

怎么樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM