简体   繁体   English

TypeScript写的一个Babel插件参数的类型是什么?

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

I am writing a Babel plugin in TypeScript and have been struggling to find a lot of examples or documentation doing so.我正在 TypeScript 中编写一个 Babel 插件,并且一直在努力寻找大量示例或文档。 For example, I am writing a visitor plugin with the following signature:例如,我正在编写一个具有以下签名的访问者插件:

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

I am getting a few types from:我从以下几种类型中得到:

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

The part that bothers me is the { types: t }: typeof babel which is coming from困扰我的部分是来自的{ types: t }: typeof babel

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

The few examples I found online were using this but is this really how it's supposed to be typed?我在网上找到的几个例子都使用了这个,但真的应该这样输入吗?

As per this open Babel issue from 2019, it looks like Babel's types are divided between '@babel/core and @babel/types .根据 2019 年的开放 Babel问题,看起来 Babel 的类型分为'@babel/core@babel/types One thing to not confuse, unlike some other "types" packages for Node, @babel/types is not a "type" package for Babel but rather contains methods for building ASTs manually and for checking the types of AST nodes.不要混淆的一件事是,与 Node 的其他一些“类型”包不同, @babel/types不是 Babel 的“类型”包,而是包含手动构建 AST 和检查 AST 节点类型的方法。 So they are basically different packages with different goals.所以它们基本上是具有不同目标的不同包。

The challenge with Babel packages is that they seem to use namespace (wildcard) imports and it doesn't seem there is any type for the packages themselves. Babel 包的挑战在于它们似乎使用命名空间(通配符)导入,而且包本身似乎没有任何类型。

One quick way to solve this:解决此问题的一种快速方法:

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
}

This makes the code more readable until this open Babel issue is fixed.这使得代码更具可读性,直到这个开放的 Babel 问题得到修复。

how about怎么样

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