简体   繁体   中英

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

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

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

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM