How to use the parse function from recast

Find comprehensive JavaScript recast.parse code examples handpicked from public code repositorys.

The recast.parse function is used to parse a string of JavaScript code into an abstract syntax tree (AST).

55
56
57
58
59
60
61
62
63
64
65
  return result;
}


const parseOptions = {
  parser: {
    parse(src) {
      return flowParser.parse(src, {
        // Comments can't cause UI strings to appear in the app; ignore them.
        all_comments: false,
        comments: false,
fork icon594
star icon0
watch icon0

25
26
27
28
29
30
31
32
33
34
35
36
describe('refactor', () => {
    describe('#flagAPIToLiteral', () => {
        it('should introduce the createdByPiranha property on the literals', () => {
            const code = 'isFlagTreated(testFlag)';


            let ast = recast.parse(code).program;
            const engine = new refactor.RefactorEngine(ast, properties, treated, flagname);
            engine.flagAPIToLiteral();


            assert(ast.body[0].expression.createdByPiranha !== undefined);
fork icon162
star icon0
watch icon43

+ 1399 other calls in file

How does recast.parse work?

The recast.parse function is a part of the Recast library and is used to parse a string of JavaScript code into an abstract syntax tree (AST). To accomplish this, the function accepts a single argument, which is the code to be parsed. The function uses the Acorn parser to convert the code into an AST that can be traversed and manipulated programmatically. The resulting AST can be used to analyze or transform the code in various ways. If the code is not valid JavaScript, an error will be thrown. By using the recast.parse function, developers can programmatically parse JavaScript code into an AST, which can be useful in scenarios where they need to analyze or manipulate the code. This can include tasks such as code formatting, linting, and refactoring.

36
37
38
39
40
41
42
43
44
45
46


describe('piranha', () => {
    describe('#sample.js', () => {
        it('featureFlag treated', () => {
            const code = fs.readFileSync('./test/input/sample.js', 'utf-8');
            const ast = recast.parse(code).program;
            const flagname = 'featureFlag';
            const behaviour = true;
            const expected_code = fs.readFileSync('./test/treated-expected/sample-featureFlag.js', 'utf-8');

fork icon162
star icon0
watch icon43

+ 279 other calls in file

24
25
26
27
28
29
30
31
32
33
var recastOptions = {
  sourceFileName: filename,
  sourceMapName: filename + '.map'
};

var ast = recast.parse(source, recastOptions);
ast = es6defaultParams.transform(es6restParams.transform(es6class.transform(ast)));
var result = recast.print(ast, recastOptions);

fs.writeFileSync(path.join(RESULTS, testName + '.js'), result.code, 'utf8');
fork icon12
star icon44
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const recast = require("recast");

const code = `
function square(x) {
return x * x;
}
`;

const ast = recast.parse(code);

console.log(ast);

In this example, we're using the recast.parse function to parse a simple JavaScript function into an AST. We define a code variable that contains a simple function definition. We use the recast.parse function to parse the function code into an AST and store it in an ast variable. We log the ast variable to the console, which will output the following: yaml Copy code

52
53
54
55
56
57
58
59
60
61
62
/** change the file key to load in different source code */
// const fileKey = "mapstd_src";
const fileKey = "xkcd_src";
const scriptString = fs.readFileSync(path.resolve(__dirname, `./temp/updated_${fileKey}.js`)).toString();
const scriptArr = scriptString.split("\n");
const ast = recast.parse(scriptString, { range: true });


/* referenced: https://github.com/airportyh/esprima_fun/blob/master/scope_chain.js. Creating a list of scopes where 0th item in each scope list is the function name or null if function is anonymous. Initialized with global 'Program' scope. TEMP OBJECT used to track CURRENT program scopes AS YOU TRAVERSE. @TODO: update for clarity */
let scopeChain = [["Program"]];

fork icon1
star icon0
watch icon6

+ 33 other calls in file

13
14
15
16
17
18
19
20
21
22
transform(code, id) {
    var transformed = false
    if (micromatch.isMatch(id, includes) && !micromatch.isMatch(id, excludes)) {
        const hasPureAnnotation = comments => comments && comments.length === 1 && (comments[0]|| {}).value === PURE_ANNO

        const ast = recast.parse(code, {
            parser: require("recast/parsers/babylon")
          });

        const b = recast.types.builders;
fork icon0
star icon2
watch icon0

225
226
227
228
229
230
231
232
233
234
// AST
var code =
  `function add(a,b){
     return a + b
   }`
const ast = recast.parse(code)
const add = ast.program.body[0].type
log(add)
const add = ast.program.body.BlockStatement.body[0]
log(add)
fork icon0
star icon0
watch icon1

+ 33 other calls in file

44
45
46
47
48
49
50
51
52
53
54
55
56
    }
}


function visitCode(code, shouldConvert) {


    var ast = recast.parse(code);


    var errors = [];
    var hasDirective = false;

fork icon0
star icon0
watch icon2

2
3
4
5
6
7
8
9
10
11
12
13
14
;


// Let us transform the order of the parameters and convert it in a functionExpression


// Parse the code using an interface similar to require("esprima").parse.
const ast = recast.parse(code, {  parser: require("espree")});
const add = ast.program.body[0];


// Notice how it is pretty printed back to the original code.
console.log(`input code:\n${recast.prettyPrint(ast, { tabWidth: 2 }).code}`);
fork icon0
star icon0
watch icon0

+ 2 other calls in file

9
10
11
12
13
14
15
16
17
18
19
20
21


const kind = KIND[process.argv[2]] || KIND.pod;
const k8scr = K8SCR[process.argv[2]] || K8SCR.pod;


const filename = `${kind.toLocaleLowerCase()}.service.ts`;
const ast = parse(getCode(kind, k8scr), {
  parser: require("recast/parsers/typescript")
});


def("File")
fork icon0
star icon0
watch icon0

+ 4 other calls in file

44
45
46
47
48
49
50
51
52
53

// Include the runtime by modifying the AST rather than by concatenating
// strings. This technique will allow for more accurate source mapping.
var runtimePath = require("..").runtime.path;
var runtime = fs.readFileSync(runtimePath, "utf8");
var runtimeBody = recast.parse(runtime, {
  sourceFileName: runtimePath
}).program.body;

var body = program.body;
fork icon0
star icon0
watch icon0

+ 3 other calls in file

386
387
388
389
390
391
392
393
394
395
  'ExportNamedDeclaration'
]
for (const file of packageJson.files.filter(x=>x.endsWith(distDtsExt))) {
  console.info('  Patching', file)
  const source = readFileSync(file, 'utf8')
  const parsed = recast.parse(source, { parser: recastTS })
  let modified = false
  for (const declaration of parsed.program.body) {
    if (!declarationsToPatch.includes(declaration.type) || !declaration.source?.value) continue
    const oldValue     = declaration.source.value
fork icon0
star icon0
watch icon0