Last active
May 1, 2016 13:01
-
-
Save mofas/f141ada14fcea8698c195fa646b15a9a to your computer and use it in GitHub Desktop.
Change all var to const
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); | |
}; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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