Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AMD Module Shaping: How to load only one JS function?

Many JavaScript libraries have a Builder tool that will allow you to "shape" what features of the library you depend on, both in terms of download bandwidth cost to the client and in terms of isolating functionality you actually need.

For example, I like many things in sugar.js, but I simply don't need or want katakana and hiragana character set handling. As the most trivial example, I want to be able to "shape" sugar.js to only export string.isBlank().

Is there a tool available to do this for me? Is there any ongoing effort by the EcmaScript committee to do something like this in a future version of JavaScript? Do any higher-level languages like TypeScript and CoffeeScript, offer hidden support for such "shaping"? I can do such "shaping" in C# for .NET DLLs via monolinker.

Basically, it looks to me like AMD handles the Loader aspect of a modern compiler, but does not handle the Linker aspect. Builders for jquery and dojo only work for a specific module, and aren't true Linkers, just Builders.

UPDATE: Google Closure Compiler is a compiler that takes JavaScript as input and produces JavaScript as output. The Advanced Compilation and Externs documentation suggests there is an API call to do this:

If putting together these export statements seems too tedious, you can use a function to do the exporting for you. See the Closure Library functions goog.exportSymbol() and goog.exportProperty() for examples of exporting functions.

However, this seems pretty convoluted, and makes me directly dependent on Google Closure Compiler. At this point, I am looking for info about future standards from the EcmaScript Committee, with regards to CommonJS, and for any wisdom from people who have thought about this problem and attempted to tackle it. Especially from fellow TypeScript developers; I don't want to have to create declare files in TypeScript for sugar.js, then use Google Closure Compiler against my TypeScript compiler output. It just sounds impossibly complex and hard to debug.

like image 558
John Zabroski Avatar asked Apr 25 '13 14:04

John Zabroski


1 Answers

Unfortunately, there's nothing built into Javascript to do this "shaping", and really what you want is a compiler anyway, since roughly one of the roles it serves is to automate "shaping" at many levels (not just with methods).

The Closure Compiler is mature and open source (JQuery is actually minified using the Closure Compiler). So if you're going to begin annotating your JS code for a compiler, it might as well be this one.

There a huge number of side benefits of using a compiler, btw. They will reduce your file sizes (and thus interpretation/run time) a great deal more than simply shaping your included libraries. And while you're developing it will produce a lot of helpful messages to catch bugs early.

like image 98
Eric Nguyen Avatar answered Nov 19 '22 22:11

Eric Nguyen