hysryt / wiki

https://hysryt.github.io/wiki/
0 stars 0 forks source link

CommonJS #96

Open hysryt opened 5 years ago

hysryt commented 5 years ago

http://wiki.commonjs.org/wiki/CommonJS

hysryt commented 5 years ago

Modules/1.0

CommonJS によるモジュールシステムの仕様。 node.js などで使用されている。 require 関数と exports オブジェクトから成る。

require 関数

モジュールのインポートには require() 関数を使用する。 require() は引数にモジュール識別子を取る。 返り値としてモジュールのオブジェクトを返す。 モジュールが返されない場合はエラーを投げる。

If there is a dependency cycle, the foreign module may not have finished executing at the time it is required by one of its transitive dependencies; in this case, the object returned by "require" must contain at least the exports that the foreign module has prepared before the call to require that led to the current module's execution.

exports オブジェクト

モジュールのAPIを追加するオブジェクト。

// モジュール側
exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
        sum += args[i++];
    }
    return sum;
};
// モジュールを使用する側
var add = require('math').add;
console.log(add(1,2));

モジュール識別子

  1. モジュール識別子は ターム/ で繋げた文字列。
  2. ターム はキャメルケースの文字列か、.、または..である必要がある。
  3. 拡張子はつけない。
  4. 相対パスか絶対パスで指定する。
  5. 相対パスの場合は require が呼び出された位置からの相対パスとなる。
hysryt commented 5 years ago

Modules/1.1

http://wiki.commonjs.org/wiki/Modules/1.1

Modules/1.0 に Modules/Meta を追加した仕様。

hysryt commented 5 years ago

Modules/1.1.1

http://wiki.commonjs.org/wiki/Modules/1.1.1