学习笔记《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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容