How to use the print function from recast

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

recast.print is a method in the Recast library that returns a pretty-printed version of a given abstract syntax tree (AST) node.

26
27
28
29
30
31
32
33
34
35
  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');
fs.writeFileSync(path.join(RESULTS, testName + '.js.map'), JSON.stringify(result.map), 'utf8');
return result.code;
fork icon12
star icon44
watch icon0

41
42
43
44
45
46
47
48
49
50
                })
                return false
            }
        })

        return transformed ? recast.print(ast).code : code;
    }
    return null;
},
generateBundle(_opts, bundles) {
fork icon0
star icon2
watch icon0

How does recast.print work?

recast.print is a function in the Recast library for printing a given abstract syntax tree (AST) node or array of nodes back into a JavaScript code string, while preserving the original formatting and comments. It walks the given AST node or array of nodes, and invokes the corresponding AST printing handler function for each node, which in turn returns a string representation of the node. These string fragments are then concatenated together, with proper whitespace and comment tokens inserted to recreate the original code formatting. The final output is a JavaScript code string.

51
52
53
54
55
56
57
58
59
60
    max_cleanup_steps,
    false,
    true,
);
engine.refactorPipeline();
const refactored_code = recast.print(ast).code;
assert(!checkForPiranhaLiterals(ast));
assert(
    expected_code === refactored_code,
    `\nEXPECTED : ${JSON.stringify(expected_code)}\nREFACTORED : ${JSON.stringify(refactored_code)}`,
fork icon162
star icon0
watch icon43

+ 279 other calls in file

78
79
80
81
82
83
84
85
86
87
  .filter(this.filterEmptyTrees);

this.visitProjectTrees(trees,visitOptions)
  .forEach(function(tree) {
    if (tree) {
      var printed = recast.print(tree.ast).code;
      if (!options.dryRun) {
        fs.writeFileSync(tree.dest, printed);
      }
      ui.writeLine(chalk.green('  updating file ') + tree.dest);
fork icon1
star icon7
watch icon1

+ 29 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
const recast = require("recast");
const { variableDeclaration, variableDeclarator, identifier } =
  recast.types.builders;

const ast = variableDeclaration("const", [
  variableDeclarator(identifier("x"), identifier("y")),
]);

const output = recast.print(ast).code;
console.log(output); // logs 'const x = y;'

In this example, we create an AST representing the statement const x = y; using the recast.types.builders module. We then pass this AST to recast.print() to generate the output code as a string, which is assigned to the output variable. Finally, we log the output string to the console.

101
102
103
104
105
106
107
108
109
110
// console.log("in enter");
if (isCorrectNodeType(node)) {
    let updateStartStr = "/* autogen added */";
    let updateEndStr = "/* autogen added */";

    let nodeStr = recast.print(node).code;
    const startLoc = node.loc.start;
    const endLoc = node.loc.end;

    /** Adding this to avoid adding an empty comment if no
fork icon1
star icon0
watch icon6

+ 4 other calls in file

67
68
69
70
71
72
73
74
75
76
    }
);

var output = undefined;
if (hasDirective && errors.length === 0 && shouldConvert) {
    output = recast.print(ast).code;
}
return {
    generatedJs: output,
    errors: errors,
fork icon0
star icon0
watch icon2

172
173
174
175
176
177
178
179
180
181
toSource(options) {
  if (this._parent) {
    return this._parent.toSource(options);
  }
  if (this.__paths.length === 1) {
    return recast.print(this.__paths[0], options).code;
  } else {
    return this.__paths.map(p => recast.print(p, options).code);
  }
}
fork icon0
star icon0
watch icon1

57
58
59
60
61
62
63
64
65
66
67
      }


      return false
    }
  })
  let code = recast.print(ast).code
  // console.log('=============')
  // console.log(code)
  return code
}
fork icon0
star icon0
watch icon0

+ 4 other calls in file

30
31
32
33
34
35
36
37
38
39
40
]);


// Switch the parameters order:
add.params.push(add.params.shift());


const output = recast.print(ast).code;


console.log(`output code:\n${output}`);
fork icon0
star icon0
watch icon0

+ 2 other calls in file

29
30
31
32
33
34
35
36
37
38
39
40
  }), d.source);
});


const service_ts = b.file(filename, b.program(imports.concat(ast.program.body[0])))


const result = print(service_ts);
fs.readdir(path.join(__dirname, '../dist'), function(err) {
  if (err) {
    fs.mkdir(path.join(__dirname, '../dist'), { recursive: true }, function(err) {
      if (err) {
fork icon0
star icon0
watch icon0

+ 4 other calls in file

403
404
405
406
407
408
409
410
411
      } else {
        console.info('    ', oldValue, 'left as is')
      }
    }
    if (modified) {
      writeFileSync(file, recast.print(parsed).code, 'utf8')
    }
  }
}
fork icon0
star icon0
watch icon0

28
29
30
31
32
33
34
35
36
37
38
    return !['-r','--rewrite','-h','--help'].includes(item)
})


let filename = clearFileArg[0]
const writeASTFile = function(ast,filename,rewriteMode){
    const newCode = recast.print(ast).code
    //非覆盖模式下
    if(!rewriteMode){
        filename = filename.split('.').slice(0,-1).concat(['export','js']).join('.')
    }
fork icon0
star icon0
watch icon0

12
13
14
15
16
17
18
19
20
21
        path.node.source = recast.types.builders.literal(`/__modules/${source}`)
      }
      this.traverse(path)
    },
  })
  return recast.print(ast).code
}


exports.transformModuleImports = transformModuleImports
fork icon0
star icon0
watch icon0

17
18
19
20
21
22
23
24
25
26
27
ast.program.body[0] = variableDeclaration('const', [
  variableDeclarator(add.id, functionExpression(null, add.params, add.body)),
])


// 将AST对象重新转回可以阅读的代码
const output = recast.print(ast).code
console.log(output)
// const add = function(a, b) {
//   return a + b
// };
fork icon0
star icon0
watch icon0