我知道requireJS支持sugar语法,下面的代码是否正确加载位于js / window / startup.js的模块,以及jquery,underscore和Backbone的依赖?
require.config({
baseUrl: 'http://localhost/js/',
path: {
jquery: '/lib/jquery-1.9.1.min',
underscore: '/lib/underscore-1.4.4',
backbone: '/lib/backbone-1.0'
}
});
require([
'./window/startup',
'jquery',
'underscore',
'backbone',
], function(Startup){
Startup.init();
});
js / window / startup.js中的代码:
define(function (require) {
var $ = require('jquery');
_ = require('underscore');
Backbone = require('backbone');
//Test to see if module is being fired
console.log('The module code has been executed!');
var init = function(){
/* SOME CODE */
//Test to see if the init function has fired
console.log('The initialize function has fired!');
}
return {
init: init
}
});
这一切似乎都符合文档,但是当我运行此代码时,两个控制台消息都没有显示。
答案 0 :(得分:2)
您的代码中存在大量语法错误。查看this plunker了解工作示例。
这是你错了:
require.config({ // NEED PARENTHESIS HERE
baseUrl: 'http://localhost/js/',
paths: { // SHOULD BE paths, NOT path
jquery: '/lib/jquery-1.9.1.min',
underscore: '/lib/underscore-1.4.4',
backbone: '/lib/backbone-1.0'
}
}); // NEED END PARENTHESIS HERE
require([
'./window/startup',
'jquery',
'underscore',
'backbone' // GET RID OF TRAILING COMMA
], function(Startup){
Startup.init();
});
在您的其他文件中:
define(function (require) { // GET RID OF EXTRA PARENTHESIS IN HERE
var $ = require('jquery'), // SHOULD BE COMMA, NOT SEMICOLON
_ = require('underscore'), // SHOULD BE COMMA, NOT SEMICOLON
Backbone = require('backbone');
//Test to see if module is being fired
console.log('The module code has been executed!');
var init = function(){ // NEED AN ASSIGNMENT, INSTEAD OF JUST var fn() {}
/* SOME CODE */
//Test to see if the init function has fired
console.log('The initialize function has fired!');
};
return {
init: init
};
}); // NEED END PARENTHESIS HERE
我强烈建议使用报告语法错误的代码编辑器。这可以帮助您避免这些问题。