学习笔记《CommonJS》

2009年1月的时候,Kevin Dangoor 写了这篇文章,开始了 CommonJS 的故事
http://www.blueskyonmars.com/2009/01/29/what-server-side-javascript-needs/

Kevin Dangoor 曾经在 Mozilla 和 Adobe 工作,目前在 可汗学院 做研发管理,由他发起和管理的 CommonJS 是一套 JS 的模块化标准,让 JS 从一种只能运行在浏览器中的小语种,发展成为了能够在服务器端和客户端运行的强大语言系统

Commonjs是一个更偏向于服务器端的规范。Node.js采用了这个规范。 根据CommonJS规范,一个单独的文件就是一个模块。加载模块使用require方法,该方法读取一个文件并执行,最后返回文件内部的exports对象。

为了解决浏览器应用场景的一些特别需求(异步加载),出现了 AMD(Asynchronous Module Definition) 标准,AMD 本身是 CommonJS 标准的变形,在国内比较流程的 CMD 也是类似的标准

《JavaScript Module Systems Showdown: CommonJS vs AMD vs ES2015》 中提到:

One evening at Joyent, when I mentioned being a bit frustrated some ludicrous request for a feature that I knew to be a terrible idea, he said to me, "Forget CommonJS. It's dead. We are server side JavaScript." - NPM creator Isaac Z. Schlueter quoting Node.js creator Ryan Dahl

stackoverflow 上有一个对 CommonJS 的解释获得了很高的评价:

CommonJS is a way of defining modules with the help of an exports object, that defines the module contents. Simply put, a CommonJS implementation might work like this:

// someModule.js
exports.doSomething = function() { return "foo"; };

//otherModule.js
var someModule = require('someModule'); // in the vein of node    
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };

Basically, CommonJS specifies that you need to have a require() function to fetch dependencies, an exports variable to export module contents and a module identifier (which describes the location of the module in question in relation to this module) that is used to require the dependencies(source). CommonJS has various implementations, including Node.js.

CommonJS was not particularly designed with browsers in mind, so it doesn't fit in the browser environment very well. Apparently, this has something to do with asynchronous loading, etc.

你可能感兴趣的:(学习笔记《CommonJS》)