twitter/rajasegar_c
Front-end Developer @ Freshworks
github/rajasegar
hangaroundtheweb.com
pradeep.naik@freshworks.com
let hello = "world";
function hello() {
console.log("hello world")
}
$ sed 's/hello/world' input.js
$ sed 's/hello/world' project1/app/**/*.js project2/app/**/*.js
let world = "world";
function world() {
console.log("world world")
}
let hello = "world";
function hello() {
console.log("hello world")
}
mounted() {
var self = this
window.addEventListener('scroll', function() {
self.scrolled = true
})
}
mounted() {
window.addEventListener('scroll', () => {
this.scrolled = true
})
}
attached: function () {
doSomething()
}
mounted: function () {
this.$nextTick(function () {
doSomething()
})
}
Update source code to fit a team’s coding conventions
Make widespread changes when an API is modified
Automate large-scale refactoring tasks
Easily update your code to take advantage of newer language features
Code Transformations
A Tree representation of the abstract syntactic structure of source code written in a programming language.
An AST is basically a DOM for your code.
function helloWorld() {
console.log('hello world');
}
function helloWorld() {
console.log('hello world');
}
{
"type": "Program",
"start": 0,
"end": 44,
"body": [
{
"type": "FunctionDeclaration",
"start": 0,
"end": 44,
"id": {
"type": "Identifier",
"start": 9,
"end": 14,
"name": "hello"
},
"expression": false,
"generator": false,
"params": [],
"body": {
"type": "BlockStatement",
"start": 17,
"end": 44,
"body": [
{
"type": "ExpressionStatement",
"start": 21,
"end": 42,
"expression": {
"type": "CallExpression",
"start": 21,
"end": 41,
"callee": {
"type": "MemberExpression",
"start": 21,
"end": 32,
"object": {
"type": "Identifier",
"start": 21,
"end": 28,
"name": "console"
},
"property": {
"type": "Identifier",
"start": 29,
"end": 32,
"name": "log"
},
"computed": false
},
"arguments": [
{
"type": "Literal",
"start": 33,
"end": 40,
"value": "hello",
"raw": "'hello'"
}
]
}
}
]
}
}
],
"sourceType": "module"
}
Codemods
RUNNER
WRAPPER
RUNNER
WRAPPER
( CLI )
( recast )
RUNNER
( CLI )
recast
esprima
ast-types
const recast = require('recast');
const code = fs.readFileSync('code.js','utf-8');
const ast = recast.parse(code);
const faster = transform(ast);
const output = recast.print(faster).code;
/**
* This replaces every occurrence of variable "foo".
*/
module.exports = function(fileInfo, api) {
return api.jscodeshift(fileInfo.source)
.findVariableDeclarators('foo')
.renameTo('bar')
.toSource();
}