RequireJS는 자바 스크립트 파일을 비동기 적으로 (즉, 차단하지 않고)로드하고 여러 자바 스크립트 파일 간의 종속성을 관리하는 데 사용되는 비동기 모듈 (AMD) API 의 구현입니다. 또한 개발자가 논리적으로 분리 된 코드를 유지하면서 배포 할 수 있도록 스크립트 파일을 결합하고 최소화하는 최적화 도구가 포함되어 있습니다.
다음 예는 RequireJS의 기본 설치 및 설정을 보여줍니다.
index.html
이라는 새 HTML 파일을 만들고 다음 내용을 붙여 넣습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello RequireJS</title>
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
</head>
<body>
<!-- place content here --->
<script>
requirejs(["scripts/say"], function(say) {
alert(say.hello());
});
</script>
</body>
scripts/say.js
에서 새 JS 파일을 만들고 다음 내용을 붙여 넣습니다.
define([], function(){
return {
hello: function(){
return "Hello World";
}
};
});
프로젝트 구조는 다음과 같아야합니다.
- project
- index.html
- scripts
- say.js
브라우저에서 index.html
파일을 열면 'Hello World'로 알려줍니다.
require.js 스크립트 파일을로드하십시오.
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
scripts
모듈에서 비동기 적으로 say
모듈을로드하십시오. (모듈을 참조 할 때 .js
확장자가 필요 없다는 것에주의하십시오.) 반환 된 모듈은 hello()
가 호출되는 제공된 함수로 전달됩니다.
<script>
requirejs(["scripts/say"], function(say) {
alert(say.hello());
});
</script>
say
모듈은 하나 개의 기능으로 하나의 객체 반환 hello
정의합니다.
define([], function(){
return {
hello: function(){
return "Hello World";
}
};
});
다음 예제는 define()
함수를 사용하여 여러 종속성을 보여줌으로써 Hello World
를 확장합니다.
index.html
이라는 새 HTML 파일을 만들고 다음 내용을 붙여 넣습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello RequireJS</title>
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
</head>
<body>
<!-- place content here --->
<script>
requirejs(["scripts/say"], function(say) {
console.log(say.hello("english"));
console.log(say.hello("spanish"));
console.log(say.hello("french"));
});
</script>
</body>
scripts/say.js
에서 새 JS 파일을 만들고 다음 내용을 붙여 넣습니다.
define(["scripts/translations"], function(translations){
return {
hello: function(language){
return translations[language].hello + " " + translations[language].world;
}
};
});
scripts/translations.js
에서 새 JS 파일을 만들고 다음 내용을 붙여 넣습니다.
define([], function(){
return {
"english": {
hello: "Hello",
world: "World"
},
"spanish": {
hello: "Hola",
world: "Mundo"
},
"french": {
hello: "Bonjour",
world: "Le Monde"
}
};
});
프로젝트 구조는 다음과 같아야합니다.
- project
- index.html
- scripts
- say.js
- translations.js
브라우저에서 index.html
파일을 열면 콘솔에서 다음과 같이 출력됩니다.
Hello World
Hola Mundo
Bonjour Le Monde
require.js 스크립트 파일을로드하십시오.
<script type="text/javascript" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
scripts
모듈에서 비동기 적으로 say
모듈을로드하십시오. (모듈을 참조 할 때 .js
확장자가 필요 없다는 것에주의하십시오.) 반환 된 모듈은 hello()
가 호출되는 제공된 함수로 전달됩니다.
<script>
requirejs(["scripts/say"], function(say) {
console.log(say.hello("english"));
console.log(say.hello("spanish"));
console.log(say.hello("french"));
});
</script>
say
모듈은 hello
정의 된 하나의 함수를 가진 단일 객체를 반환하지만, 여기서는 종속성 ( scripts/translations
)을 정의하고 거기에서 변환을 가져올 것입니다.
define(["scripts/translations"], function(translations){
return {
hello: function(language){
return translations[language].hello + " " + translations[language].world;
}
};
});
translations
모듈은 단순히 다양한 단어 번역이있는 객체를 반환합니다.
define([], function(){
return {
"english": {
hello: "Hello",
world: "World"
},
"spanish": {
hello: "Hola",
world: "Mundo"
},
"french": {
hello: "Bonjour",
world: "Le Monde"
}
};
});
모든 라이브러리가 AMD 및 RequireJS의 define()
함수와 호환되는 방식으로 정의되지는 않습니다. 저자는 이러한 종속성을 구성하기위한 shim
지시문을 포함 shim
문제를 해결했습니다.
한 가지 예는 jQuery UI 레이아웃 플러그인을 사용하는 것입니다. 그 플러그인은 jQuery에 의존한다. 다음과 같이 설정할 수 있습니다 :
requirejs.config({
paths: {
'jquery': '../path/to/jquery.min',
'jquery.layout': '../path/to/jquery.layout.min'
},
shim: {
'jquery.layout': {
deps: ['jquery']
}
}
});
그리고 다음과 같은 레이아웃 모듈에서 사용하십시오 :
define(['jquery', 'jquery.layout'], function ($, layout) {
$('body').layout();
});
<script>
태그에있는 data-main
을 사용하여 RequireJS로 애플리케이션에 대한 단일 진입 점이 가능합니다.
<script type="text/javascript" data-main="scripts/main" src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
로드 할 때 RequireJS는 data-main
속성을 찾고 async
속성이 설정된 DOM에 주 스크립트 태그를 삽입합니다. 이 파일은 응용 프로그램을 시작하기 전에 구성을 원할 것입니다.
예 :
// contents of scripts/main.js
require.config({
waitSeconds: 10,
paths: {
jquery: 'libs/jquery-1.4.2.min'
}
});
requirejs(["jquery", "libs/say"], function($, say) {
var $body = $('body');
$body.append( $('<p/>').text(say.hello("english")) );
$body.append( $('<p/>').text(say.hello("spanish")) );
$body.append( $('<p/>').text(say.hello("french")) );
});