我不时听说CommonJS http://www.commonjs.org/是一种创建一组模块化javascript组件的努力,但坦率地说,我从来没有理解过它。
我可以使用的这些模块化组件在哪里?我在他们的主页上看不到太多。
发布于 2010-11-26 07:16:39
CommonJS只是一个标准,指定了一种模块化JavaScript的方法,因此CommonJS本身并不提供任何JavaScript库。
CommonJS指定了一个require()函数,它允许用户导入模块并使用它们,这些模块有一个特殊的全局变量,名为exports,它是一个保存要导出的内容的对象。
// foo.js ---------------- Example Foo module
function Foo() {
this.bla = function() {
console.log('Hello World');
}
}
exports.foo = Foo;
// myawesomeprogram.js ----------------------
var foo = require('./foo'); // './' will require the module relative
// in this case foo.js is in the same directory as this .js file
var test = new foo.Foo();
test.bla(); // logs 'Hello World'Node.js标准库和所有第三方库都使用CommonJS来模块化它们的代码。
再举一个例子:
// require the http module from the standard library
var http = require('http'); // no './' will look up the require paths to find the module
var express = require('express'); // require the express.js framework (needs to be installed)发布于 2010-11-26 07:16:49
这个想法似乎(我没有意识到这一点)是要为不仅仅是web浏览器提供javascript。例如,CouchDB支持javascript进行查询。
发布于 2017-02-10 02:34:44
CommonJS不是一个模块,它只是一个定义两个JavaScript模块应该如何相互通信的规范。本规范使用exports variable和require函数来定义模块如何公开和使用彼此。
为了实现CommonJS规范,我们有很多遵循CommonJS规范的开源JS框架。JS加载器的一些例子有systemJS、Webpack、RequireJS等。下面是一个简单的视频,它解释了CommonJS,并演示了systemJS如何实现通用的js规范。
https://stackoverflow.com/questions/4281436
复制相似问题