Large scale Code Modification
Muhammad Ammar Hasan
- BE Software Engineering from NED University
- Application Developer at Recurship
Changes to a large number of files in our codebase
- change in an API
- deprecations in libraries
-
enforce consistent code style
Problem
Approaches
- block or postpone the changes to a later date
- search-and-replace -> cumbersome, impractical
(i.e. never)
-> Technical debt
Regex
- hard/complex
- different code conventions
- do not understands the code in context,
error prone
Codemods are scripts used to rewrite other scripts
Regex on steroids
write code to modify code
- a toolkit for codemods ( programmatically make massive changes to your JavaScript codebase)
- approachable API that feels syntactically similar to jQuery
parse
find
create
update
Abstract Syntax Tree (AST)
BabelJS uses it to transform your code from ES6 to ES5. ESLint uses it to lint your code.
https://astexplorer.net/
back to jscodeshift..
Setup
npm i -g jscodeshift
jscodeshift -t path-to-transform.js input-file.js
it can be a glob/ folder
module.exports = function(fileInfo, api) {
// transform `fileInfo.source` here
// ...
// return changed source
return source;
};
let write our first codemod
Conclusion
learned a quick and easy way to do code refactoring
-> less reluctant to upgrade libraries and change APIs
Shamelessly copied material from following links to prepare this presentation
- https://github.com/sejoker/awesome-jscodeshift
- https://www.toptal.com/javascript/write-code-to-rewrite-your-code
- https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb
- https://testing-mines.blogspot.com/2016/06/write-code-to-rewrite-your-code.html
- https://medium.com/@btegelund/migrating-code-using-codemods-808e2e29e5f2
- https://medium.com/@andrew_levine/writing-your-very-first-codemod-with-jscodeshift-7a24c4ede31b
Bonus
awesome-angular
awesome-nodejs
awesome-*
CodeMod
By Ammar Hasan
CodeMod
- 491