I am very new to jscodeshift. Is it possible to get code line by line.
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source).forEach(p => {
p.value.program.body.forEach(p => {
console.log(p)
});
}).toSource();
}
But the problem with this approach is such that i can't apply transformations to the resultant obtained in the variable p
. For example. For the input below
var a = "hello";
var b = "stackoverflow";
var c = a + b;
I need to transform the content line by line. is it possible to apply transformation line by line in jscodeshift.
You can use .get().node.program.body
and loop over that:
http://astexplorer.net/#/gist/fea38e8a6837d227fd02cb1297824280/be3b1fb941ee3e6dfbe4eea86610a3ad48e2b511
This:
const transformer = (file, api) => {
const j = api.jscodeshift;
const root = j(file.source);
root.get().node.program.body.map((line) => {
line.kind = "const";
});
return root.toSource();
};
export default transformer;
Transforms:
var a = "hello";
var b = "stackoverflow";
var c = a + b;
To:
const a = "hello";
const b = "stackoverflow";
const c = a + b;
You didn't ask for an exact transformation, so I just provided an example that morphed each line.
But you should note that the advantage of an Abstract Syntax Tree is that you do not need to go line by line. If you are able to provide what transformation you are looking for, it is likely that the community could provide you with a better solution than looping line by line.