CommonJS模块在哪里?

时间:2010-11-25 23:09:10

标签: javascript node.js commonjs

我不时听说CommonJS http://www.commonjs.org/是一种创建一组模块化javascript组件的努力,但坦率地说,我从来没有理解任何内容。

我可以使用这些模块化组件在哪里?我在他们的主页上看不多。

3 个答案:

答案 0 :(得分:16)

CommonJS只是一种指定模块化JavaScript的方法的标准,因此CommonJS本身不提供任何JavaScript库。

CommonJS指定一个require()函数,它允许导入模块然后使用它们,模块有一个名为exports的特殊全局变量,它是一个保存将被导出的东西的对象。 / p>

// 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)

答案 1 :(得分:1)

似乎(我不知道这一点)的想法是提供javascript而不仅仅是Web浏览器。例如,CouchDB支持javascript进行查询。

答案 2 :(得分:0)

CommonJS不是一个模块,它只是一个定义两个JavaScript模块应该如何相互通信的规范。该规范使用exports变量和require函数来定义模块如何相互公开和消费。

为了实现CommonJS规范,我们有许多遵循CommonJS规范的开源JS框架。 JS加载器的一些示例是systemJS,Webpack,RequireJS等。下面是一个解释CommonJS的简单视频,它还演示了systemJS如何实现常见的js规范。

Common JS视频: - https://www.youtube.com/watch?v=jN4IM5tp1SE

相关问题