Skip to content

Instantly share code, notes, and snippets.

@mofas
Last active May 1, 2016 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mofas/f141ada14fcea8698c195fa646b15a9a to your computer and use it in GitHub Desktop.
Save mofas/f141ada14fcea8698c195fa646b15a9a to your computer and use it in GitHub Desktop.
Change all var to const
//Example: https://astexplorer.net/#/E25QuXone4
//test_1.js
var var1 = 'var';
//we want to change it to
//const var1 = 'var';
//start template
export default function transformer(file, api) {
const j = api.jscodeshift;
const {expression, statement, statements} = j.template;
return j(file.source)
//Using find to locate the code you want to modified
//the first argument will be the type of targeting code.
//the second arguments could be an object which is the subset of AST you want to find
.find(j.VariableDeclaration, {
kind: 'var',
})
//Using replaceWith or forEach to modified the source code you find
//if you want to replace all node you find directly, use replaceWith directly.
//However, if you only want to modify part of those code, or you want to further filter.
//Then you could use forEach to execute more precise manipulation
.forEach(p=>{
p.value.kind = 'const';
return p;
})
.toSource();
};
//test.js
var var1 = 'var';
const var2 = 'var2';
var bar = 'bar';
bar = 'foo';
//Now we need to handle more complex scenario
//We need to check whether variables are reassigned or not.
export default function transformer(file, api) {
const j = api.jscodeshift;
const {expression, statement, statements} = j.template;
return j(file.source)
.find(j.VariableDeclaration, {
kind: 'var',
})
.forEach(p=>{
//TODO ....
p.value.kind = 'const';
return p;
})
.toSource();
};
//Actually it is too complex to write down to here.
//Please refer https://github.com/cpojer/js-codemod/blob/master/transforms/no-vars.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment