"use strict"; prepended blindly to scripts in the wild

Mark S. Miller erights at google.com
Wed Sep 8 22:31:51 PDT 2010

I recently asked Kris Kowal what he recommends as the simplest way to write
simple JS "modules" today that can be used either as browser-side scripts or
as CommonJS modules. Adapting the elegant pattern he showed me, I suggest
the following variation:

(function(require, exports) {
  "use strict";
  // ...
  exports.x = 21;

        typeof require === 'function' ? require :
          function(id) { return this[id]; },
        typeof exports !== 'undefined' ? exports : (this.foo = {}));

(function(require, exports) {
  "use strict";
  var foo = require("foo");
  // ...
  exports.y = foo.x * 2;

        typeof require === 'function' ? require :
          function(id) { return this[id]; },
        typeof exports !== 'undefined' ? exports : (this.bar = {}));

In a CommonJS environment, "require" and "exports" would be defined and
"require" would be a function, so the first branches of the ?:s above would
be taken. In a browser-side environment, they wouldn't be defined, so the
second branches would be taken. In a CommonJS environment, loading bar.js
would cause the loading of foo.js. In a browser-side environment, the page
would still have to manually include these scripts in bottom-up order as
usual -- first foo and then bar. This works whether foo.js and bar.js are
included as separate scripts or whether they are appended together. Fancier
adapters like <http://requirejs.org/> do more but need more setup. When the
simple pattern above is adequate, it works without any prelude or

Everything above should work on old ES3 browsers. On ES5 browsers, each
individual module is strict, without the strictness leaking when module
sources are appended.

The main limitation for browser-side use is that the module names become
global variable names, and so potentially conflict with other global
variable names.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20100909/d29ef2b8/attachment-0001.html>

More information about the es-discuss mailing list