4

I am writing a Babel plugin in TypeScript and have been struggling to find a lot of examples or documentation doing so. 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

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?

Nicolas Bouvrette
  • 4,295
  • 1
  • 39
  • 53

2 Answers2

5

As per this open Babel issue from 2019, it looks like Babel's types are divided between '@babel/core and @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. 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.

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.

Nicolas Bouvrette
  • 4,295
  • 1
  • 39
  • 53
0

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(...)
}
rou
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 19 '23 at 10:57