Ska
Ska

Reputation: 6888

How to get code as a string from Babel node during traverse

In the below code, is it possible to get the whole string representation of the AST node which would in this case return the window.alert('asdf')?

const ast = parse("window.alert('asdf')")

let preloadCode = ""
traverse(ast, {
  CallExpression: function(path) {
    // path.node.toString() ??
  },
})

Upvotes: 3

Views: 4216

Answers (5)

morganney
morganney

Reputation: 13560

If writing a plugin using babel >= 7.22.5 you can do this:

export default function () {
  return {
    visitor: {
      CallExpression(path, state) {
        const { node } = path
        const { code } = state.file

        console.log(code.slice(node.start, node.end))
      }
    }
  }
}

Upvotes: 0

Eugene
Eugene

Reputation: 2701

@babel/traverse, version 7.18.3

Just use path.toString():

const ast = parse("window.alert('asdf')")

traverse(ast, {
   CallExpression: function(path) {
      console.log(path.toString());
   },
})

Found it here

Upvotes: 2

Sr. Oshiro
Sr. Oshiro

Reputation: 160

There is a method https://npmdoc.github.io/node-npmdoc-babel-core/build/apidoc.html#apidoc.element.babel-core.traverse.NodePath.prototype.getSource

const ast = parse("window.alert('asdf')")

let preloadCode = ""
traverse(ast, {
  CallExpression: function(path) {
    // path.node.toString()
    path.getSource() 
  },
})

Upvotes: 1

futpib
futpib

Reputation: 589

Each AST node returned by @babel/parser has a start and end properties pointing to it's location in the source code. You can use those to slice the source for the original string.

const { parse } = require('@babel/parser');

const source = '1 + 2 + 3';
const ast = parse(source);
const node = ast.program.body[0].expression.left;

console.log(source.slice(node.start, node.end)); // → '1 + 2'

Upvotes: 6

futpib
futpib

Reputation: 589

You are probably looking for https://babeljs.io/docs/en/babel-generator

Try this:

const { default: generate } = require('@babel/generator');

module.exports = () => ({
    visitor: {
        Identifier: (path, state) => {
            console.log(generate(path.parent));
        },
    },
});

Upvotes: 3

Related Questions