0
export default function({ types: t }) {
  return {
    pre(state) {
      this.allString = '';
    },
    visitor: {
      StringLiteral(path) {
        this.allString += path.node.value;
      }
    },
    post(state) {
      // It does not work
      state.code = `const allString = '${this.allString}'\n` + state.code;
    }
  };
}

For example, I want to add a variable that contains all the strings in the code, is it possible to be done by one plugin?

HZ1
  • 1

2 Answers2

0

done

post(state) {
  state.ast.program.body.push(t.variableDeclaration('const', [
    t.variableDeclarator(t.identifier('allString'), t.stringLiteral(this.allString))
  ]));
}
HZ1
  • 1
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 25 '22 at 08:48
0

The state variable in the post method has an ast attribute and a path attribute you can use to modify the code. For instance:

export default function({ types: t }) {
  return {
    visitor: {
      // Do preparation work in this visitor
    },
    post(state) {
      state.path.traverse({
        // Do code changes in this one
      })
    }
  };
}

Alternatively, you could do your checking via the pre method (since it has the same signature as the post) and then use the visitor for the actual code changes.

Tim Brown
  • 3,173
  • 1
  • 18
  • 15