Writing Babel plugin, how to modify code after visitor?

48 Views Asked by At
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?

2

There are 2 best solutions below

1
HZ1 On

done

post(state) {
  state.ast.program.body.push(t.variableDeclaration('const', [
    t.variableDeclarator(t.identifier('allString'), t.stringLiteral(this.allString))
  ]));
}
0
Tim Brown On

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.