typescriptbabeljstypescript-typingsbabel-plugin

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. 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?


Solution

  • 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.