Search code examples
javascriptangularabstract-syntax-tree

Best way to find and replace old components using Angular + Nx


I have an Nx monorepo, with three Angular apps (all version 14), and a lib with some UI components.

I want to create an NX executor that finds and replaces old components with newer ones. For example:

<!-- What I have -->
<my-button-component></button>

<!-- What I want -->
<button my-button></button>

I need a script for this because there are multiple components to be replaced and multiple instances of each component. So my team decided to create a script.

Now, how would I go about doing this? I created the executor, but how do I actually analyze the project, update the modules and etc...

I was thinking about ngast, but I couldn't get it to work :/ I don't think it supports Angular 14.

I'm not even sure if AST is the tool for the job. I need a light here, please. Is there a proper tool for this?


Solution

  • One of the ways you can achieve this is forking @angular-eslint/eslint-plugin-template. It has processors that are using @angular-eslint/template-parser to parse Angular Templates.

    Your plugin can look some kind similar to:

    export default createESLintRule<[], MessageIds>({
      create(context) {
        const parserServices = getTemplateParserServices(context);
        const source = context.getSourceCode();
        
        return {
          [`Element$1[name=my-button-component]`](element: TmplAstElement) {
            context.report({
              node: node,
              message: "Use 'button' instead of 'my-button-component'",
              fix: function(fixer) {
                const elementText = source.getText(element);
                const newText = elementText.replace('my-button-component', 'button');
                
                return fixer.replaceText(element, newText);
              }
          });
        }
      }
    }
    

    You can also use button-has-type (source) as an example and read about applying fixes in ESLint docs.