Javascript 모듈 관리엔 RequireJS

자바스크립트 모듈이 많아 관리가 어렵다면, RequireJS를 사용 해 보세요.

설정(Configuration)


require.config({
"baseUrl": "/static/js/vendor",
"paths": {
"app": "../app",
"bootstrap": [
'//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min',
"bootstrap"
],
"jquery": [
"//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min",
"jquery-1.9.1.min"
],
"can": "can",
shim: {
"bootstrap": {
deps: ["jquery"],
exports: "$.fn.popover"
},
enforceDefine: true
}
}
});

모듈 정의(define function)


define(["jquery"],function($){
return {
getParam: function(paramname){
var value = new RegExp('[\?&]' + param
name + '=([^&#]*)').exec(window.location.href);
return value[1];
},
test: function(text){
console.log("test : "+text);
}
};
});

두 모듈을 한 파일에 넣는 방법(requirejs, two classes in one file)

http://stackoverflow.com/questions/9806940/requirejs-two-classes-in-one-file

define('test', ['jquery'], function() {
var exports = {};
exports.test1 = {
method1 : function () {
console.log("test1 - method 1");
},
method2 : function () {
console.log("test1 - method 2");
}
};
exports.test2 = {
method1 : function () {
console.log("test2 - method 1");
},
method2 : function () {
console.log("test2 - method 2");
}
};

return exports;
});

그리고 아래처럼 사용하면 된다.
require(['test'], function (test) {
var test1 = test.test1;
});

두 모듈을 한 파일에 넣는 다른 방법
http://blog.credera.com/topic/technology-solutions/java/modular-javascript-with-requirejs


define(['json!data/customers'], function(customers){
var getRow = function(id) {
return customers[id];
};

var getAll = function() {
return customers;
};

var update = function(data) {
// do something cool with the data
};
return {
get: getRow,
list: getAll,
update: update
};
});


오류 해결

  • Jquery CDN경로가 올바르지 못할 경우 Bootstrap로딩에 오류가 난다.
  • 같은 모듈(예: bootstrap)이 중복 로드될 경우 충돌이 일어난다.

RequireJS 홈페이지



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!