incubator-callback-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From James Burke <jrbu...@gmail.com>
Subject Re: CommonJS and AMD (and, not or)
Date Tue, 13 Dec 2011 22:52:42 GMT
On Tue, Dec 13, 2011 at 1:43 PM, Patrick Mueller <pmuellr@gmail.com> wrote:
> This is using the anonymous module pattern, instead of naming the module by
> passing an id as the first parameter to define().  Unfortunately, it seems
> difficult to convert this pattern into almond usage, as almond requires
> that you have an id as the first parameter (as near as I can tell, for a
> normal module).  To use an anonymous module with almond, you have to
> rewrite the module to add the id at build time (ick!) or you could resort
> to horrible, hideous hacks (you don't want to know!).

Yes, the build step needs to inject a module ID as part of
concatenating anonymous modules together. It is not that bad (a regexp
can handle it), or use r.js, the requirejs optimizer.

Using the requirejs optimizer also allows running AMD loader plugins
as part of build so things like i18n bundles, text templates can be
inlined in the built file. As simple file concat will not get that.
r.js is just a single JS file, runs in node or rhino.

> A named, wrapped CJS module as AMD would look like:
>
> define(moduleId, function(require, exports, module){
>   //CJS stuff goes in here.
> })
>
> I'm not sure what breaks when you DO use an id; is that an issue with
> dynamic loading?

You can manually code in a module ID as part of the JS source, and it
will load, but it is not considered best practice. You lose some
flexibility with renaming/moving the file in that case (you then need
to remember to open the file and edit the name).

Naming modules is really a build task anyway. It would have to be done
for CJS modules that get wrapped. While in the CJS case it is just a
simple function wrapping, using a regexp applied to in-source
anonymous define() calls gives these benefits:

* more flexibility in file renaming/moving
* the in-source wrapping shorter
* modules can be loaded dynamically, and the developer does not *have*
to make sure everything is built into one file or converted to a
format the browser will understand.

For me, that is a reasonable tradeoff, particularly since there are
tools that can do the work today. In addition to the requirejs
optimizer, there is one in dojo, and curl's builder, cram, can do that
naming work too.

If AMD loader plugins look interesting to use, particularly during a
build, then using a full AMD-aware builder will be needed anyway,
since it actually runs the loader plugins during the build step to get
their output to inject into the built file.

James

Mime
View raw message