CommonJS模块在哪里?

有时候我会听说CommonJS http://www.commonjs.org/是为了创build一组模块化javascript组件,但坦率地说,我从来没有理解任何东西。

这些模块化组件在哪里可以使用? 我没有看到太多的主页。

CommonJS只是一个标准的模块化JavaScript,所以CommonJS本身不提供任何JavaScript库。

CommonJS指定了一个require()函数,它可以导入模块然后使用它们,模块有一个名为exports的特殊全局variables,它是一个包含将被导出的东西的对象。

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

这个想法,似乎(我没有意识到这一点),是提供JavaScript不仅仅是网页浏览器。 例如, CouchDB支持javascript查询。

CommonJS不是一个模块它只是一个规范,它定义了两个JavaScript模块应该如何相互通信。 这个规范使用了exportsvariables,并且需要函数来定义模块将如何公开和消耗对方。

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

常见的JSvideo: – https://www.youtube.com/watch?v=jN4IM5tp1SE