CommonJS Feature Discussions
This is the second part of a chronicle of the CommonJS modules debate,
reconstructed from the list archive.
The first part has the timeline and the
method.
This one is about the module itself: whether it gets its own scope, whether
it may import everything another module exports, what require returns,
how a module exports, and the two kinds of module identifier.
Each design point is drawn as an IBIS outline: the issue, the positions with who took them, the arguments for and against, and the resolution. Every node links to the message that carries it.
A scope of one's own #
Issue: does a module's code run in the global scope or in a scope of its own?
- The global scope, like a
<script>tag. Peter Michaux began there, and Tom Robinson held out longest for a Ruby-stylerequirethat evaluates a file globally.- For: "The VAST majority of the time I just want to do: require("File") and have access to the File object." Browser libraries already namespace themselves with objects (Tom).
- Against: a missing
varpollutes everything, which matters more on a server, with more code (Kevin Dangoor's summary).
- A module scope, with
require(Hannes Wallnoefer's Pythonic Modules, from Helma NG).- For: "a language that scales to projects with more lines of code and developers" (Hannes).
- A module scope where only
require,exportsand the primordials are free (Securable Modules, which Ihab Awad introduced for the two of us).- For: tools can check a module for dangling free variables, and a module has only the authority it is given.
- Resolution. Peter was won over on IRC, and Kevin's show of hands came back unanimous. Securable Modules became Modules/1.0.
Most of the rest of this article is about the consequences of that choice. Once a module had a scope of its own, every other question was about what could cross into it.
Wildcard imports: the case against include #
My own 2008 module standard had an
include.
It took everything another module exported and bound it in the importing
module's scope, the way Python's from module import * does.
I could not imagine a community adopting a module system without one.
The list did, in about three days.
Hannes's Helma NG had all three forms:
import('helma.file'); // helma.file.File
include('helma.file'); // File, and every other export
var file = require('helma.file'); // file.File, named by the importer
Issue: should the standard let a module bring all of another module's exports into its own scope?
- Standardize
require,importandincludetogether. Hannes, on January 30, and Tom Robinson, who found that "in every case where I call "require" so far, I could have used "import" / "include"." I was on this side at first, with a large body of Chiron code that used it.- For: "no Python person in one's right mind would trade python's module system for something less flexible" (Hannes).
- For: a column of
importcalls reads better than a column ofvar foo = require('foo')(Hannes). - For: Helma's
includecopied only the exported properties, and the copied functions still closed over their home module (Hannes).
- Standardize only
require; let implementations offerincludeas an extension. Peter Michaux, after Hannes won him over on IRC, and then Hannes himself.- For:
require"explicitly shows all things used in a particular file. Better than wondering where something was loaded" (Peter). - For: the standard should hold the minimum;
includeandimport"can easily be implemented on top of require()" (Hannes). - For: if
includewere standard, a compliant library could use it, and "the whole global clobbering issue returns" (Peter).
- For:
- An
includethat names what it takes, which I floated asinclude("greet-en", ["greet"]).- Against: it needs an
importsobject and awithblock around the module, which "blows static lexical analysis of free variables out of the water," as I wrote at the time. - Against: destructuring would do the same job safely:
var {greet} = require("greet-en").
- Against: it needs an
- Resolution. On February 2, 2009, Hannes
removed
"the description of include(), import(), and export(), leaving just
require()," because "it now better represents what most people can agree
on."
The next day I
called it
"the "include" function we have both redacted from our requirements," and
by the end of the month I had a
"use iojs"mode in my loader to wean my own modules off it.
The argument that settled it for me was in that same message to Tom: "there's nothing like actually having sovereignty in your own name spaced file to give you peace of mind, especially when you're sharing your name space with unknown, potentially malicious peers."
Implementations kept include for a while as an extension.
v8cgi's
filled the global scope
with a module's exports.
Node had one too, until Ryan Dahl removed it on October 5, 2009, writing that
"include() should not be used by libraries because it will pollute the
global namespace. To discourage this behavior and bring Node more in-line
with the current CommonJS module system, include() is removed"
(nodejs/node 8185e1fd25).
Three days later the question came back in a thread about QUnit, and I explained why I had changed sides:
This opens an old wound; it was amply discussed in January and I was originally on the pro-include side of the debate with a large body of code using it already. I agree that it's convenient; but I've been convinced it's a bad idea for standardization because, we can frankly live without it [...], and eventually we'll be able to use destructuring like var {F} = r("f") which is about as convenient and safe. It's also become quite obvious to me that while going from require to include would be easy, it is extraordinarily difficult to do the reverse since information about which free variables are in use and where they are from is effectively lost. If that's difficult for the author of a body of code, it's impossible for someone trying to learn how your code works.
Kevin Dangoor
thought
include was "nice as an extension" for the rare cases where he would use
from something import * in Python.
Hannes
still used it
"all the time," for modules whose exported names stand on their own, like
assertEquals.
Neither asked for it back in the standard.
I would put the asymmetry first now.
A wildcard import is a one-way door: the author saves a line, and every
later reader, and every later version of the imported module, pays for it.
That is the hazard I describe in How to design a module
system, and CommonJS closed that door by leaving
include out.
What require returns #
Issue: is the object require returns the module's own exports, or
something standing in front of it?
I called for hands on five options, A through E, and Peter Michaux added F:
- A. A frozen snapshot of the exports.
- B. A function that looks up exports by name, giving read-only access to the live object. Peter preferred it, and it was Mark S. Miller's first choice before he abstained: he expected to write secure code at the loader level, where none of the options threatened anything.
- C. A proxy that inherits from the exports, which Chris Zumbrunn favored as protection against accidental mutation.
- D. A copy, as of the call.
- E. The original exports object, which the module may freeze itself.
- F. A live, read-only proxy, Peter's restatement of B.
- Resolution. E, from twelve of the people who answered, with George Moschovitis's reason the most common one: "the other proposed methods alter the nature/feeling of JS." Snapshots, which were my idea, were rejected in favor of late binding, and as I said later, "I don't miss it; late binding is handy."
E is why two modules can require each other.
Ihab
told the history
in December:
"Historically, Kris Kowal's and my first thought about modules was that
they would construct and return the exported object. We quickly realized
that this caused problems when modules require() one another in a cycle."
The loader passes the module an exports object before running it, and in a
cycle, require hands back that object half built.
Replacing the exports object #
Which brings us to the first decision the list could not make.
Issue: may a module export a single value, a constructor say, in place of the object it was given?
require.setExports(value), latermodule.setExports, throwing if anyone has already required the module. Isaac Schlueter proposed it in December 2009, and I supported it.- For:
var Foo = require("foo").Foo; var myFoo = new Foo;is, in Isaac's words, "a lotta foo," and one module could not otherwise proxy another. - For:
var $ = require("jquery"), as I put it.
- For:
- Assign
module.exports, which Node already allowed because it exposed its module object.- Against: Isaac noted that a guarded setter needed ES5 accessors that not every engine had.
require.export(MyModule), and noexportsfree variable at all (Ryan Dahl).- Make
exportscallable:exports({β¦}), my own bike-shed color.- Against:
exports.name = β¦fails silently on a function, andnew exports()is strange. "No, I think, as cute as it is, if we're gonna treat something as a bag of data, it should be a regular object" (Isaac).
- Against:
- No replacement.
- For: the provided object exists for cycles, and replacing it brings back the problem it solved (Ihab).
- For: GPSEE's exports objects carried a finalizer and native properties; "we have previously specified the behaviour of the properties of the object returned by require(); we are now specifying the behaviour of the object itself" (Wes Garland).
- For: "The original modules proposal, with only a simple "require" and "exports", had a pleasing minimality and taste. With the addition of "module" and now "setExports", this is being rapidly lost" (Mark S. Miller).
- Resolution. No standard.
I
held
that "we should not ratify it as a standard until all of the engines are
willing to implement it," and they were not.
The specification kept saying, as Modules/1.1.1 still does, that "modules
must use the "exports" object as the only means of exporting."
Mikeal Rogers
raised it again
in October 2010 with a
returnstatement as a third spelling, after he and I spent most of JSConf on it. Node keptmodule.exports, and by May 2011 Mikeal could report that "non-standard additions like module.exports are being implemented widely, which was added by node. The CommonJS list tried to standardize that addition and hit a dead end."
So the most common line in the npm ecosystem today is one the CommonJS specification never allowed:
module.exports = function Foo() {};
The list was right that replacing the exports object breaks cycles, and
the ecosystem was right that people wanted to export one thing.
Node's choice won by shipping, not by argument.
Years later, ESM's export default was added for parity with
module.exports, as the last part tells.
Two kinds of identifier #
The distinction between relative and so-called absolute identifiers is one I wrote down myself, "based on some feedback, and some personal preference (based on minimizing the amount of effort I'll have to do to port the scripts I've got)," as I admitted at the time.
On February 6, 2009, I wrote:
1.) A module identifier is a String of "terms" delimited by forward slashes.
2.) A term must be a camelCase identifier, ".", or "..".
3.) The extension of the file corresponding to a module identifier must be inferred by loaders.
4.) Module identifiers may be "relative" or "absolute". A module identifier is "relative" if the first term is "." or "..".
5.) Absolute identifiers are resolved off the conceptual name space root. A loader may check multiple roots in a consistent order, like a PATH.
6.) Relative identifiers are resolved relative to the file in which "require" is called.
Issue: which identifiers are relative, and what are the others relative to?
./and../mark the relative ones; everything else resolves from the root of the module namespace, as above.- For: "Relative identifiers are only useful if you have a tree of packages that would benefit from being decoupled from the identifier of their container" (me). When Peter asked whether Java got by without them, I answered: "Yes, for values of "get by" that are equal to "eclipse refactoring tools that rewrite your code for you" or meta packaging."
- For: project skeletons that move as a unit (Starr Horne).
- The Unix convention: plain names are relative, and a leading slash is
absolute.
Peter Michaux
proposed it
that day: "I'd say we want to write require('File') rather than
require('./File')."
Ben Newman
asked again
a year later.
- Against: "you have no way of knowing what directory I have installed my libraries in" (Wes Garland).
- Against: Ben's own conclusion, after the thread: the choice "seems to reflect the empirical judgment that including top-level standard modules is more common (and should look cleaner) than including relative client code" (Ben).
- Dotted or reverse-domain names,
com.corp.module(Michael O'Brien). - Resolution. The first position, which Modules/1.0 spells as
"relative" and "top-level": no file extensions,
.or..first for a relative identifier, and "Top-level identifiers are resolved off the conceptual module name space root." Node adopted it on October 31, 2009, in a commit titled "Module refactor - almost CommonJS compatible now," whose summary readsrequire("/sys.js") becomes require("sys")andrequire("circle.js") becomes require("./circle")(7a2e784ad7). - Later. I call it a coin-toss now. I do not know that I called it right, but I still feel vindicated for insisting on a distinction (part 4).
A second issue followed from the first: relative to the requiring module's identifier, or to its file? I argued for the identifier, because "it must be possible for module loaders to be created for systems that are not on a file system," and because path-relative resolution could give two files the same identifier. Wes argued for the file, since a module asking for its sibling should get its sibling. The specification says the identifier. In practice, with one file per module and one directory per package, the two readings rarely differ.
What the specification did not settle was who owns the top-level names. I thought I knew. When Ben Newman asked how to graft a foreign library under a prefix of his own, when its modules used top-level identifiers among themselves, I answered: "This is a big problem with absolute identifiers. As a matter of practice, we should only use absolute identifiers for CommonJS modules, but that is not yet really feasible." And in April 2010, at greater length, "The top-level module identifier name space belongs to CommonJS."
That is not how it went.
In Node and npm, a top-level identifier came to name a package, looked up
from the requiring module's own node_modules and its ancestors'.
How that happened, and what the list proposed instead, is in
the third part.
Module metadata and the 1.x revisions #
The other decisions about the module were smaller, and the shows of hands settled them.
In June 2009 I called for hands on
Modules/Meta,
which gave require a main and a paths, and gave every module a
module object with an id, such that require(module.id) returns the
same exports.
The wiki marks it "ratified and integrated in Modules/1.1."
Node renamed its module.name to module.id "for commonjs compat"
(f683867b98) the same day it went "almost CommonJS compatible."
Modules/1.1.1, in March 2010, fixed what require.main is when there is no
main module.
The draft said an empty object; Hannes wanted undefined, so that 1.1.1
would be a strict extension of 1.0, and he got it.
The text that resulted is the one that makes a familiar idiom work:
require.main "must either be undefined or be identical to the "module"
object in the context of one loaded module."
if (require.main === module) {
main();
}
The page lists the hands: Mikeal, Gozala, Zach Carter, Hannesw, Tobie, OndΕej Ε½Γ‘ra, Charles Jolley, KrisKowal, Chris Zumbrunn, Gmsox.
require.paths did not last.
Changing it at run time "was never more than a stop-gap," as I
put it
in 2011, and "the require.paths.push(".") pattern needs to go away."
Node removed it that July (7f0047c2d5).
Transport, and the split with AMD #
The browser was the list's longest argument, and it ended in a split rather than a decision.
Issue: what wrapper does a browser loader use to receive CommonJS modules through script tags?
- Transport/B: a build target that wraps a module and passes in its free variables, which I posted in December 2009.
- Transport/C:
require.def(id, dependencies, factory), the dependencies injected as arguments, James Burke's, which he compared with mine in March 2010. - One
definefor both, as Kris Zyp proposed in September 2010 and soon renamed "Asynchronous Module Definition."- Against: the thread ran to "~230 posts since Sept 1," and Wes Garland named the premise he thought false: "require(X) does not work in the browser."
- Resolution. AMD stayed a proposal on the wiki. In May 2011 James Burke offered to take it elsewhere, and I agreed: "It isn't a CommonJS specification because it hasn't received a near-unanimous blessing from this community. [...] It's a reboot, not an evolution. [...] So, yes. I'm in favor of redirecting AMD to RequireJS."
Through all of it I held that require takes only a string literal, so that
a loader in a browser can find a module's dependencies before running it.
I meant CommonJS primarily for the web, and
the last part follows that thread to ESM.
The JavaScript Modules Chronicle:
- The CommonJS Dialectic
- CommonJS Feature Discussions
- CommonJS Packaging
- CommonJS Retrospective
- Previous: The CommonJS Dialectic
- Next: Interoperable JavaScript Modules