facebook / jscodeshift

A JavaScript codemod toolkit.
https://jscodeshift.com
MIT License
9.22k stars 477 forks source link

Help: How do I get hold of Decorator nodes? #535

Open klippx opened 1 year ago

klippx commented 1 year ago

How do I get a hold of the collection for @Directive() and @ObjectType() and Field() decorator calls in this example?

https://astexplorer.net/#/gist/96fa2a58a3c859d61278839d7b897f8f/acf963ec5bd8c96799d87bf4f8ccf6504c24c6d6

I have tried

module.exports = function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);

  // Nothing! But isn't this exactly what the selector is supposed to find?
  const decorators = root.find(j.Decorator); 

  // A lot, but none of the decorators
  const identifiers = root.find(j.Identifier); 

  // Finds the `@Field()` decorator, but also includes the `visualizations` property which is too much.
  const classProperties = root.find(j.ClassProperty);   

  return root.toSource();
};

I want to find them and only them so I can remove those lines of code with j.remove(path).

My config looks like this:

const options = {
  dry: true,
  print: true,
  verbose: 1,
  parser: 'babylon',
  parserConfig: {
    sourceType: 'module',
    allowImportExportEverywhere: true,
    allowReturnOutsideFunction: true,
    startLine: 1,
    tokens: true,
    plugins: [
      'typescript',
      ['decorators', { decoratorsBeforeExport: true }],
    ],
  },
};
ludgerey commented 7 months ago

I have the same issue.

Basically this makes mods impossible for Class Decorators.