admin管理员组

文章数量:1287258

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() ??
  },
})

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() ??
  },
})
Share Improve this question asked Apr 20, 2020 at 15:17 SkaSka 6,90815 gold badges54 silver badges75 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

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'

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));
        },
    },
});

@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

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() 
  },
})

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))
      }
    }
  }
}

本文标签: javascriptHow to get code as a string from Babel node during traverseStack Overflow