Search code examples
babeljstypescript-decorator

Unable to parse class method decorator in a Babel plugin


I'm writing a Babel plugin that manipulates the AST node related to a specific decorator. I'm traversing the AST but for some reason, my plugin doesn't detect the method decorator - node.decorators is always null when the visitor visits a node.

This is the plugin:

import { ClassMethod, Decorator } from '@babel/types';
import { get } from 'lodash';
import { NodePath, PluginObj } from '@babel/core';

const providerArgumentsTransformer = (): PluginObj => ({
  visitor: {
    ClassMethod({ node, parent }: NodePath<ClassMethod>) {
      const decorator = getProviderDecorator(node.decorators); // <- node.decorators is always null
      if (getDecoratorName(decorator) === 'Provides') {
        console.log('Success');
      }
    },
  },
});

function getProviderDecorator(decorators: Array<Decorator> | undefined | null): Decorator | undefined {
  return decorators?.find((decorator) => get(decorator, 'expression.callee.name') === 'Provides');
}

function getDecoratorName(decorator?: Decorator): string | undefined {
  return get(decorator, 'expression.callee.name');
}

export default providerArgumentsTransformer;

I'm testing the decorator as follows:

import { PluginObj } from '@babel/core';
import * as babel from '@babel/core';
import providerArgumentsTransformer from './providerArgumentsTransformer';

const code = `class MainGraph {
  Provides(clazz, propertyKey, descriptor) { }

  @Provides()
  someString(stringProvider) {
    return stringProvider.theString;
  }
}`;

describe('Provider Arguments Transformer', () => {
  const uut: PluginObj = providerArgumentsTransformer();

  it('Exposes transformer', () => {
    babel.transformSync(code, {
      plugins: [
        ['@babel/plugin-proposal-decorators', { legacy: true }],
        ['@babel/plugin-proposal-class-properties', { legacy: true }],
        [uut, { legacy: true }],
      ],
      configFile: false,
    });
  });
});

I wonder if the issue is related to how babel.transformSync is used or perhaps the visitor is not configured properly.


Solution

  • Turns out the decorators were missing because @babel/plugin-proposal-decorators clears the decorators when it traverses the AST.

    In order to visit the node before @babel/plugin-proposal-decorators I had to modify my visitor a bit. This approach should probably be optimized by visiting ClassBody or ClassExpression instead of Program.

    const providerArgumentsTransformer: PluginObj = {
      visitor: {
        Program(path: NodePath<Program>) {
          path.traverse(internalVisitor);
        },
      },
    };
    
    const internalVisitor = {
      ClassMethod: {
        enter({ node }: NodePath<ClassMethod>) {
          // node.decorators are not null anymore
        },
      },
    };