JSTransform
A simple utility for pluggable JS syntax transforms using the esprima parser.
- Makes it simple to write and plug-in syntax transformations
- Makes it simple to coalesce multiple syntax transformations in a single pass of the AST
- Gives complete control over the formatting of the output on a per-transformation basis
- Supports source map generation
- Comes pre-bundled with a small set of (optional) ES6 -> ES5 transforms
Examples
Using a pre-bundled or existing transform:
var es6ClassVisitors = require('jstransform/visitors/es6-class-visitors').visitorList;
var fs = require('fs');
var jstransform = require('jstransform');
var originalFileContents = fs.readFileSync('path/to/original/file.js', 'utf-8');
var transformedFileData = jstransform.transform(
es6ClassVisitors,
originalFileContents
);
console.log(transformedFileData.code);
Using multiple pre-bundled or existing transforms at once:
var es6ArrowFuncVisitors = require('jstransform/visitors/es6-arrow-function-visitors').visitorList;
var es6ClassVisitors = require('jstransform/visitors/es6-class-visitors').visitorList;
var jstransform = require('jstransform');
var originalFileContents = "var a = (param1) => param1; class FooClass {}";
var transformedFileData = jstransform.transform(
es6ClassVisitors.concat(es6ArrowFuncVisitors),
originalFileContents
);
console.log(transformedFileData.code);
Writing a simple custom transform:
var jstransform = require('jstransform');
var Syntax = require('esprima-fb').Syntax;
var utils = require('jstransform/src/utils');
function visitEvalCallExpressions(traverse, node, path, state) {
utils.append('alert("...eval?...really?...");', state);
utils.catchup(node.range[1], state);
}
visitEvalCallExpressions.test = function(node, path, state) {
return node.type === Syntax.CallExpression
&& node.callee.type === Syntax.Identifier
&& node.callee.name === 'eval';
};
var originalFileContents = "eval('foo');";
var transformedFileData = jstransform.transform(
[visitEvalCallExpressions],
originalFileContents
);
console.log(transformedFileData.code);