Modules in JavaScript; The next big question
Posted by Dion Almaer 11 months ago on javascript modules
One of JavaScript’s weaknesses has been that of modularization. Born from the land of <script> we have lived the life of #include. Our function(){} wrappers and checks are to #ifdef.
We could get away with this when we were sprinkling Ajax dust into web pages via jQuery, but as soon as you get larger, you find yourself building some kind of dependency / package management system. The community has certainly offered up a lot of choice in that regard, and with CommonJS and node… along came many more.
Now that JavaScript is evolving again (once Harmony was reached) we can look to attack the problem head on and TC-39 is doing just that with their Module work.
Isaac has just written an interesting piece on ES6 modules from his perspective (which is an important one having creating npm and now leading node.js).
He first takes a look at the issues with loaders in the wild, and then offers up a potential solution…. which interestingly doesn’t have a module formal keyword.
The current implementations:
- Impose boilerplate restrictions on the programmer. This is ugly and error-prone, and there is no easy way to catch many of these errors early.
- Are not inter-operable with code that uses a different module system (or none at all).
- Either require that all modules be present in the page at the start, or delay the execution of the program unacceptably. (No one does sync XHR. I’m talking about r.js/AMD and the YUI3 seed file here.)
- Leaks internal implementation details in unfortunate ways, so that users are sometimes surprised when behavior violates intuitions.
- Do not isolate global leakage, making a missing var a felony, when it shouldn’t even be a misdemeanor. (At best, they wrap in a function.)
- To varying degrees, line and column numbers are obscured. (Sometimes just the first line’s column; sometimes the stack traces are completely meaningless.)
These days JavaScript isn’t just about a browser, but at the same time it is the only viable option inside the browser. We need to take care at how we codify modules as we will be stuck with the implications for a long time to come. We need to get it right.