Modernization: Global Variable to CommonJS Conversion
This was a solo project I worked on here and there. It started out as a proof of concept to showcase the power of the JavaScript Abstract...
This was a solo project I worked on here and there. It started out as a proof of concept to showcase the power of the JavaScript Abstract Syntax Tree and codemods, but it didn't take long before it morphed into something much more ambitious. It was huge, challenging project that kept increasing in complexity as I uncovered more important details and edge-cases.
We have dozens of JavaScript modules, each with their own repository on our internal GitHub. Many of them were written before Node's CommonJS pattern, so they expose their functionality using global namespacing for use in our web applications that are full of legacy browser-ready ES5 code. Global namespacing is old and hard to maintain. Module patterns are the future. So I wanted to replace global namespacing with CommonJS!
This doesn't do the size and complexity of the project any justice, but these were the major parts. I wrote code to automate all of these steps:
- Clone all of the GitHub repositories from several GitHub users
- Read through all of the source code in all of the modules and extract all variable declarations and references
- Find out which are global, and ignore local variables
- Determine whether each global is native JS (window, Math), a third-party library (lodash, jquery), or an in-house namespace
- Record all namespace definitions and references to build a module dependency graph, showing where each namespace is defined, including third party globals
- Replace all namespace definitions with "module.exports", adding extra code to immediately invoke initialization functions, whenever they exist.
- Replace all namespace references with local variables, each initialized at the top of the file with a "require" to the appropriate file or module, determined by the dependency graph
Node.js
Abstract syntax tree
JavaScript
View more
Node.js
Abstract syntax tree
JavaScript
Codemods
View more