Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run babel's babylon.parse on multiple files

Tags:

babeljs

I can load one file and traverse it with babel, it goes something like this:

var babylon = require("babylon");
let contents = fs.readFileSync("example.js","utf-8");
let ast = babylon.parse(contents);

Now the question is, how can I get the AST (Abstract Syntax Tree) if I have multiple files in my program.

main.js

export const getFoo(){
  return "a"
}

example.js

import {getFoo} from './main'
let bar = getFoo() + "baz";

Obviously I would like to see the function declaration and the function call expression into the same AST, but also at the same time getting the line numbers and columns (node.loc) information to also show the specific file.

like image 828
Ska Avatar asked Sep 08 '25 07:09

Ska


1 Answers

You can concatenate the AST from several files if you know their paths and can load them.

import {parse} from '@babel/parser';

const a = 'var a = 1;'; // or fs.readFileSync("a.js","utf-8");
const b = 'var b = 2;'; // or fs.readFileSync("b.js","utf-8");
const astA = parse(a, { sourceFilename: 'a.js' });
const astB = parse(b, { sourceFilename: 'b.js' });
const ast = {
  type: 'Program',
  body: [].concat(astA.program.body, astB.program.body)
};

Source example

But I can't find out how to get AST from several files without loading them directly. I tried to write a babel plugin to analyze code from an imported file and I haven't realized how to do that.

like image 86
Den Avatar answered Sep 13 '25 05:09

Den



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!