Question

Although JavaScript and its many libraries (jQuery, RequireJS) allow for the creation of many great websites I find its lack of type safety daunting when contemplating building a larger website.

Google has a wonderful closure compiler which allows you to annotate your JavaScript with JSDoc and have it type check. Having experimented with its rich type system I expect this would greatly improve the maintainability of a longer lived JavaScript project.

The only problem is it doesn't play very nicely with AMD libraries like RequireJS. There is an experimental --transform_amd_modules flag that concatenates your JavaScript files and handles scoping by eliminating it. However this seems to be a bit of an anti-pattern, removing most of the benefits of RequireJS (but keeping the modular file structure). There's also the question of how much future support that will get

With the end goal being type-safety not at the expensive of RequireJS's benefits what would be my best bets?

PS: Although I've used RequireJS as the AMD library of choice I would not be against a solution that worked with a different AMD library.

Was it helpful?

Solution

Although the Closure Compiler may be used with various JavaScript libraries, the greatest benefit is achieved when used with the Closure Library, which has its own module and dependency system. Web applications using the Closure Library are generally compiled into one JavaScript file, which does not require asynchronous module loading. However, Closure does provide support for modules, which may be loaded asynchronously. Chad Killingsworth provided a good example of how to set up modules here. In addition, the plovr tool provides addition module support to simplify their usage.

If you have decided to use the Closure Compiler (and you are not tied to a large AMD codebase), you will likely maximize productivity by adopting the Closure Library and its module/dependency system in your new code. If you do plan to use an AMD codebase, then as you mentioned, the new experimental Compiler flags --transform_amd_modules and --process_common_js_modules may help, but when using unannotated libraries you miss out on much of the power of the Compiler.

Looking to the future, if ECMAScript Harmony modules become an official standard, then it is likely that libraries such as Closure, Dojo, and YUI will eventually conform to that standard. This might finally make it possible to seamlessly integrate JavaScript code from disparate libraries. In the meantime, if you want to write JavaScript applications and enjoy type checking, dead-code elimination, minification, advanced memory management, browser-agnosticism, and a phenomenal standard library, then I highly recommend using the Closure Compiler in conjunction with the Closure Library.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top