I am faced with the challenge of transitioning a fairly large app (~650 files) that currently has a mix of ES6 modules and legacy global namespace internal modules and classes.
My goal is to convert everything to 100% ES6 modules.
Considering an Iterative Approach
To achieve this, I first need to convert all the global objects to ES6 modules by adding the "export" keyword.
However, as soon as I add "export", the global object becomes non-global and each file using that object will throw a compiler error "object not found" (i.e. Cannot read property 'xxx' of undefined).
To resolve this issue, I must add an "import" statement to the file, thereby switching it to an ES6 module which in turn removes the global status of all objects in that file, causing new "object not found" errors in other files.
In essence, this incremental approach seems to have its drawbacks.
Potential Simpler Solution:
- Go through all ts files
- Add
export
to all top-level classes, modules, and variables programmatically. - Compile these into a list.
- Add
- Create a barrel (globalBarrel) file that re-exports all the exports gathered in the previous step.
- Revisit all ts files
- Add
to each file.import {list, of, symbols, exported, by, the, barrel,file} from "./globalBarrel"
- Add
- Attempt a clean compilation?
- Expect some circular dependency issues which need to be resolved.
- For future file edits, utilize the vsCode "Organize Imports" command to eliminate unnecessary imports.
As quoted by @jfriend000:
Trying to automatically convert non-modular code into modules will likely result in chaos.
Transitioning everything to modules at once could simplify the true modularization process.
Questioning the Best Approach
Is this method the most effective? Any suggestions?