Turbocharged JavaScript Refactoring with Codemods

Joe Lencioni
Apr 27, 2016 · 7 min read
Before codemods
After codemods

Tactics

git diff
git add --patch
git checkout --patch
git checkout --ours path/to/conflict
find app/assets/javascripts -name *.jsx -not -path */vendor/* | \
xargs jscodeshift -t ~/path/to/transform.js

Codemods that Worked Well for Us

Lightweight codemods

[1, 2, 3].map(function(x) {
return x * x;
}.bind(this));
[1, 2, 3].map(x => x * x);
var belong = 'anywhere';
const belong = 'anywhere';
const things = {
belong: belong,
anywhere: function() {},
};
const things = {
belong,
anywhere() {},
};
const belong = 'anywhere', welcome = 'home';
const belong = 'anywhere';
const welcome = 'home';
const things = {
'belong': 'anywhere',
};
const things = {
belong: 'anywhere',
};

Heavyweight Codemods

const BelongAnywhere = React.createClass({
// ...
});
class BelongAnywhere extends React.Component {
// ...
}
git checkout --ours path/to/conflict
class BelongAnywhere extends React.Component {
render() {
return <div>Belong Anywhere</div>;
}
componentWillMount() {
console.log('Welcome home');
}
}
class BelongAnywhere extends React.Component {
componentWillMount() {
console.log('Welcome home');
}
render() {
return <div>Belong Anywhere</div>;
}
}
const belong = 'anywhere '+ welcomeHome;
const belong = `anywhere ${welcomeHome}`;

Resources

Impact

Check out all of our open source projects over at airbnb.io and follow us on Twitter: @AirbnbEng + @AirbnbData

Airbnb Engineering & Data Science

Creative engineers and data scientists building a world where you can belong anywhere. http://airbnb.io

Joe Lencioni

Written by

Web infrastructure at @airbnb, obsessing over webperf. Follow @lencioni on Twitter. he/him Minnesotan.

Airbnb Engineering & Data Science

Creative engineers and data scientists building a world where you can belong anywhere. http://airbnb.io