【问题标题】:Where are the CommonJS modules?CommonJS 模块在哪里?
【发布时间】:2010-11-25 23:09:09
【问题描述】:

我不时听说 CommonJS http://www.commonjs.org/ 是在努力创建一组模块化的 javascript 组件,但坦率地说,我对此一无所知。

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

【问题讨论】:

    标签: javascript node.js commonjs


    【解决方案1】:

    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 标准库和所有第 3 方库都使用 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)
    

    【讨论】:

    • 所以 CommonJS 只指定了 require()?而已?当你阅读它时,它听起来比它“更大”:)
    • @wend 好吧,它还定义了一个匿名包装函数来封装模块内容,但是该函数的外观如何由实现决定,require 函数和exports 对象就是全部实现必须共享什么。所以,是的,他们网站上的所有规范和标准听起来都很大:D
    • 那么 commonJS 只是大多数库采用的一种导出方式?不是派生出来的一段代码,而是可以随时和JS一起使用,无需任何安装?
    【解决方案2】:

    这个想法似乎(我不知道这一点)是为不仅仅是网络浏览器提供 javascript。比如CouchDB支持javascript查询。

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-04
        • 2016-05-05
        • 2019-07-26
        • 2015-09-30
        • 2015-07-01
        • 2018-03-28
        相关资源
        最近更新 更多