Programing

CommonJS, AMD 및 RequireJS 간의 관계?

crosscheck 2020. 9. 29. 07:18
반응형

CommonJS, AMD 및 RequireJS 간의 관계?


저는 여전히 CommonJS, AMD 및 RequireJS에 대해 매우 혼란 스럽습니다. 많이 읽은 후에도.

CommonJS (이전의 ServerJS)는 언어가 브라우저 외부에서 사용될 때 일부 JavaScript 사양 (예 : 모듈)을 정의하는 그룹이라는 것을 알고 있습니다. CommonJS 모듈 사양에는 Node.js 또는 RingoJS와 같은 구현이 있습니다.

CommonJS, AMD (Asynchronous Module Definition) 및 RequireJS의 관계는 무엇입니까? RequireJS는 CommonJS 모듈 정의의 구현입니까? 그렇다면 AMD는 무엇입니까?


RequireJSAMD API (소스)를 구현합니다 .

CommonJSexports모듈 내용을 정의 하는 객체 의 도움으로 모듈을 정의하는 방법입니다 . 간단히 말해서 CommonJS 구현은 다음과 같이 작동 할 수 있습니다.

// someModule.js
exports.doSomething = function() { return "foo"; };

//otherModule.js
var someModule = require('someModule'); // in the vein of node    
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };

기본적으로 CommonJS는 require()종속성을 가져 오는 함수, exports모듈 내용을 내보내는 변수 및 종속성을 요구하는 데 사용되는 모듈 식별자 (이 모듈과 관련하여 해당 모듈의 위치를 ​​설명 함)가 있어야 함을 지정합니다 ( 소스 ). CommonJS에는 언급 한 Node.js를 포함한 다양한 구현 이 있습니다.

CommonJS는 브라우저를 염두에두고 특별히 설계되지 않았기 때문에 브라우저 환경에 잘 맞지 않습니다 ( 실제로 이에 대한 소스가 없습니다 . RequireJS 사이트를 포함 하여 모든 곳에서 그렇게 말합니다 . ) 분명히 이것은 무언가를 가지고 있습니다. 비동기 로딩 등으로 할 수 있습니다.

반면에 RequireJS는 브라우저 환경에 맞게 설계된 AMD를 구현합니다 ( source ). 분명히 AMD는 CommonJS Transport 형식의 스핀 오프로 시작하여 자체 모듈 정의 API로 발전했습니다. 따라서 둘 사이의 유사점. AMD의 새로운 기능 define()은 모듈이로드되기 전에 종속성을 선언 할 수 있도록하는 기능입니다. 예를 들어 정의는 다음과 같습니다.

define('module/id/string', ['module', 'dependency', 'array'], 
function(module, factory function) {
  return ModuleContents;  
});

따라서 CommonJS와 AMD는 구현이 다르지만 둘 다 동일한 출처에서 온 JavaScript 모듈 정의 API입니다.

  • AMD 는 모듈 종속성의 비동기로드를 지원하기 때문에 브라우저에 더 적합합니다.
  • RequireJSAMD 의 구현이며 동시에 CommonJS 의 정신을 유지하려고합니다 (주로 모듈 식별자에서).

더욱 혼란스럽게하기 위해 RequireJS는 AMD 구현이면서 CommonJS 래퍼를 제공하므로 CommonJS 모듈을 RequireJS와 함께 사용하기 위해 거의 직접 가져올 수 있습니다.

define(function(require, exports, module) {
  var someModule = require('someModule'); // in the vein of node    
  exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
});

나는 이것이 일을 명확히하는 데 도움이되기를 바랍니다!


CommonJS 는 그 이상입니다. JavaScript를위한 공통 API와 생태계를 정의하는 프로젝트입니다. CommonJS의 한 부분은 모듈 사양입니다. Node.js와 RingoJS는 서버 측 JavaScript 런타임이며 예, 둘 다 CommonJS 모듈 사양을 기반으로 모듈을 구현합니다.

AMD (Asynchronous Module Definition)는 모듈의 또 다른 사양입니다. RequireJS 는 아마도 가장 널리 사용되는 AMD 구현입니다. CommonJS와의 한 가지 주요 차이점은 AMD는 모듈이 비동기 적 으로로드되도록 지정한다는 것 입니다. 즉,로드가 완료 될 때까지 대기하여 실행을 차단하는 것과 반대로 모듈이 병렬로로드된다는 의미입니다.

AMD는 일반적으로 이로 인해 클라이언트 측 (브라우저 내) JavaScript 개발에 더 많이 사용되며 CommonJS 모듈은 일반적으로 서버 측에서 사용됩니다. 예를 들어, RequireJS 제공의 - 그러나, 당신은 어느 환경에서 각 모듈의 사양을 사용할 수 있습니다 Node.js를 실행하기위한 방향browserify는 브라우저에서 실행할 수있는 CommonJS 모듈 구현입니다.


짧은 대답은 다음과 같습니다.

CommonJS AMD 는 자바 스크립트 애플리케이션에서 모듈 및 해당 종속성을 선언하는 방법에 대한 사양 (또는 형식)입니다.

RequireJS 는 AMD와 호환되는 스크립트 로더 라이브러리이며 curljs 는 또 다른 예입니다.

CommonJS 준수 :

Addy Osmani의 책 에서 발췌 .

// package/lib is a dependency we require
var lib = require( "package/lib" );

// behavior for our module
function foo(){
    lib.log( "hello world!" );
}

// export (expose) foo to other modules as foobar
exports.foobar = foo;

AMD 규격 :

// package/lib is a dependency we require
define(["package/lib"], function (lib) {

    // behavior for our module
    function foo() {
        lib.log( "hello world!" );
    }

    // export (expose) foo to other modules as foobar
    return {
        foobar: foo
    }
});

Somewhere else the module can be used with:

require(["package/myModule"], function(myModule) {
    myModule.foobar();
});

Some background:

Actually, CommonJS is much more than an API declaration and only a part of it deals with that. AMD started as a draft specification for the module format on the CommonJS list, but full consensus wasn't reached and further development of the format moved to the amdjs group. Arguments around which format is better state that CommonJS attempts to cover a broader set of concerns and that it's better suited for server side development given its synchronous nature, and that AMD is better suited for client side (browser) development given its asynchronous nature and the fact that it has its roots in Dojo's module declaration implementation.

Sources:


Quoting

AMD:

  • One browser-first approach
  • Opting for asynchronous behavior and simplified backwards compatibility
  • It doesn't have any concept of File I/O.
  • It supports objects, functions, constructors, strings, JSON and many other types of modules.

CommonJS:

  • One server-first approach
  • Assuming synchronous behavior
  • Cover a broader set of concerns such as I/O, File system, Promises and more.
  • Supports unwrapped modules, it can feel a little more close to the ES.next/Harmony specifications, freeing you of the define() wrapper that AMD enforces.
  • Only support objects as modules.

It is quite normal to organize JavaScript program modular into several files and to call child-modules from the main js module.

The thing is JavaScript doesn't provide this. Not even today in latest browser versions of Chrome and FF.

But, is there any keyword in JavaScript to call another JavaScript module?

This question may be a total collapse of the world for many because the answer is No.


In ES5 ( released in 2009 ) JavaScript had no keywords like import, include, or require.

ES6 saves the day ( released in 2015 ) proposing the import keyword ( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/import ), but no browser implements this.

If you use Babel 6.18.0 and transpile with ES2015 option only

import myDefault from "my-module";

you will get require again.

"use strict";
var _myModule = require("my-module");
var _myModule2 = _interopRequireDefault(_myModule);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

This is because require means the module will be loaded from Node.js. Node.js will handle everything from system level file read to wrapping functions into the module.

Because in JavaScript functions are the only wrappers to represent the modules.

I'm a lot confused about CommonJS and AMD?

Both CommonJS and AMD are just two different techniques how to overcome the JavaScript "defect" to load modules smart.

참고URL : https://stackoverflow.com/questions/16521471/relation-between-commonjs-amd-and-requirejs

반응형