Doing this as a gist, because I don't have time for a polished post, I apologize:
If you had to define an optimal module system that had to work with async, networked file IO (the browser) what would that look like? It would not be node's system, for the following reasons:
- the
require('')
in node is very imperative. It can be called at any time and mean a module should be synchronously loaded and evaluated when it is encountered. How would this work if this call is encountered in the browser case:require(someVariable + '/other')
? How would you know what module to include in any bundle? For those cases, you should allow for an async require to fetch, and leave dependencies that can be bundled to therequire('StringLiteral')
format. Node has no allowance for this, and browserify will not do a good job with those types of dependencies. It will need hints, or explicit out-of-module listing of what to include.
Once you have an MVC system in the browser, it will be common to delay loading of a view and its controller until it is needed, and rely on routing via URLs or button actions to know what module to imperatively ask for next. This works well in AMD since it has a callback-style require for this. This really helps performance: the fastest JS is the JS you do not load. This is a very common practice in use with AMD systems. browserify cannot support it natively. The suggestion when using browserify is to choose your own browser script loader and figure out the loading yourself.
- Similarly, since there is no synchronous module fetching and execution in the browser (at least it would be madness to want to do that), you cannot reliably preload a modifier to the module system so that it takes effect for the rest of the module loading. Example in node is requiring coffeescript in your top level app so that any .cs files are considered in module loading.
Instead, AMD has loader plugins that allow you to specify the type of resource that is being requested. This is much more robust, and leads to better, explicit statements of dependencies. Plus, loader plugins can participate in builds. This is better than the browserify plugins for this type of thing because of the imperative nature of JS code: fs.readFile(someVariable + 'something.txt')
.
Static declaration of dependencies is better for builds. So if you like builds, favor a system that enforces static declaration, and has an async form for non-declarative module uses. ES modules will go this route, and explicitly not use node's module system because of this imperative dependency issue that node has.
The parts that are ugly about AMD:
- It explicitly asks for a function wrapper. Node actually adds one underneath the covers when it loads modules. browserify does too when it combines modules. While it would be nice to not have the function wrapper in source form, it has these advantages:
a) Using code across domains is much easier: no need to set up CORS or restrict usage to CORS enabled browsers. You would be amazed by how many people would have trouble with this as it is a hidden, secondary requirment. So, they are developing just fine on their local box, do a production deployment, then things don't work. This is confusing and not obvious as to why it fails. You may be fine with knowing what to do for this, but the general population still has trouble with this.
b) Avoids the need to use eval(). Eval support in the browser is uneven traditionally (scope differences), and now with CSP makes it even more of a hazard to use. I know there has been at least once case of a "smart" proxies that would try to "protect" a user by stripping out eval statements in JS.
In short, the function wrapper is not the ideal, but it avoids hard to trace secondary errors, and it really is not that much more typing. Use the sugar form if you want something that looks like commonjs/node.
- Possibility for configuration blocks: front end developers have much more varied expectations on project layout. Node users do not. This is not the fault of requirejs or other AMD loaders though. At the very least, supporting a configuration block allows more people to participate in the benefits of modular code.
However, there is a convention in AMD loaders of baseUrl + module ID + '.js'
. If a package manager lays out code like this, then there is no config block needed in an AMD loader. volo does this.
npm could even do this to bridge the gap: when installing a package called dep
, put it at node_modules/dep
and create a node_modules/dep.js
that just requires dep
's main module. That would also then work for AMD loaders (if the modules installed were AMD compatible or converted) if the baseUrl was set to node_modules
.
So, it is entirely possibly to stick with the AMD convention and avoid config blocks. Package manager tools have not caught up yet though. Note that this is not the fault of the core AMD module system. This is a package manager issue. And frankly, package managers have been more focused on layouts that make it easy for them vs. what is best for the runtime use and that avoid user configuration. This is the wrong decision to make. Making it easier for users and runtimes does not actually make it that much more complicated for the package manager.
On package managers:
It is important to separate what a package manager provides and what the runtime module system provides. For example, it is possible to distribute AMD-based code in npm. amdefine can help use that code in a node environment. Particularly if the dep.js
style of file is written out in the node_modules directory.
I would suggest that npm only be used for node-based code though, to reduce confusion on what can be used where. Particularly given the weaknesses of node's module system for browser use. However, some people like to distribute code targeted for the browser in node because they like npm. So be it.
But also note that a strength for node-based npm use, nested node_modules for package-specific conflicting dependencies, is actually a weakness for browser use: while disk space is cheap for node uses, delivering duplicate versions of code in the browser is really wasteful. Also, there is not a need for compiled C code dependencies in the browser case. So some of npm's capabilities around that are unneccessary.
It would be better to use a different type of package manager for front end code that tried to reuse existing module versions installed, possibly warn the user of diffs, but if really needed, then write out an AMD map config in the case that it is really needed.
In closing:
My biggest complaint is that node explicitly ignored browser concerns when designing itself and choosing its module system, but then some people want to use those design decisions and force them on browser use of modules, where they are not optimal. Just as node did not want to compromise to meet existing browser uses of JS, I do not want to use a less-capable module system in the browser.
I am hopeful that ES modules will have enough plumbing to avoid the function wrapper of AMD. But be aware that ES semantics will much more like AMD's than node's. And the ES module loader API will be robust enough to support config options and AMD loader plugins.
But note: this is not to say that someone cannot use node modules with npm and browserify to make something useful that runs in the browser. Far from it. But it will be restricted to the constraints above. There are still wonderful things that fit in that box, so more power to them for constraining themselves to that box and still shipping something useful. There is just more to browser-based module usage though. And I do not want their unwillingness to address that wider world as a reason to accept less for myself. The good news is that the internet is big enough for both sets of users. So let's all hug and move on to just making things.
(note this is a gist, so I am not notified of comments. I may delete this at some point if I get around to doing something more polished for a blog post, or just do not want to see its rough form any more)
I think Browserify is a step in the wrong direction for front-end web development. File system dependencies like node.js have almost nothing to do with the web browser run-time. To me it seems like nothing more than a case of "if all you have is a hammer, everything looks like a nail."
I get it, people got REALLY in to 1970s style Unix programming over the last few years. Everyone switched to Vim or Emacs. Ya'll really love your file descriptors and pipes! And that's absolutely fine, for code running in a Unix runtime.
However, front-end javascript does not run in a Unix runtime. It runs in the browser. It is basically in a completely different universe, a universe that has no concept of files and owes more to predecessors like Self and Smalltalk than to anything Unix related. Self and Smalltalk, while being inspirational to JavaScript in language semantics and philosophy, also share very similar runtime environments, where files and "code-compile-run" have no place.
Having a dependency management system based on Unix and files is basically like flying the airplane while sitting on the wing, well outside of the cockpit.
I've been working on a project built on top of RequireJS called lit. The current alpha version is up at http://www.corslit.com.
The basic premise is that modules are written to and read from the network. Nothing ever hits your filesystem. Hell, nothing ever hits a filesystem anywhere, as it is store in memory in Redis.
Check out this page: http://www.corslit.com/williamcotton/FutureTwin:Bolinas
It should look very familiar to AMD. However, because the function is serialized and stored on a remote server, a simple call to lit.build() instantaneous turns it in to this: http://www.corslit.com/v0/williamcotton/FutureTwin:Bolinas-v0.0.5.js
I have found npm to be very inspirational in this process. I love that lib sizes are so small, which I feel is a reflection of the ease of publication. However, there is still overhead in the form of git repos, package.json files, READMEs, submissions to npm, etc, etc... it may not SEEM like much but something like lit takes orders of magnitude less time to publish, seconds as opposed to minutes.
This drives down the size of published modules to something more atomic, the function level. There is an incredible amount of inefficiency at the function level. Every JS lib has a deep clone, an array helper, a UUID generator, a cookie reader, an XHR wrapper, etc, etc. Sure those only take minutes to write, but all of those minutes add up! Also, it leads to silos of code. Why don't Angular and Ember share more resources? Why do they have function after function that do the exact same thing, written twice in each code base? Maybe because as it stands now, publishing a 5 line function to the community seems like too much work for so little?
I really feel like git itself is the culprit for a lot of this. Git was written with a monolithic codebase in mind, the linux kernal. It was NOT written for how we're writing applications these days on the cutting edge. A node projects is basically 2% custom code and 98% code coming from other authors. We've already blended the distinction between "version control" and "package management" in our processes, but our tools are not designed with that in mind.
The npm build process is very slow because of all of the network IO. With lit it is damned near instantaneous as the code is built right out of memory. It fully allows for multiple versions of the same module, in a manner like npm.
Also, lit isn't gunning for npm. It is gunning for Bower. I can't for the life of me understand Bower. You use a package manager (npm) to install a package manager (Bower) that is basically just the first package manager. It doesn't DO anything remotely related to the browser, it just downloads things from GitHub. Why not just use npm for that if you're wanting to do things the Unix way? What does Bower do at all?
lit is NOT ready for primetime yet. However, I'm doing most of my work in it. It has even fully self-hosted for front-end code: http://www.corslit.com/williamcotton/lit
You guys should really check out Self and Smalltalk. And not just the languages, but the systems. They don't make sense when separated from their systems. We need IDEs for JavaScript that are built in and run in the web browser.