我正在尝试将JQuery
包含在使用maven
构建的网络应用中,使用RequireJS
定义Javascript
个模块。
我遵循了RequireJS
文档here,其中说明了如何将JQuery
与RequireJS
一起使用。我还有一个maven
版本。
这就是我的所作所为:
我的main.js,由RequireJS
HTML
的数据主要调用
define(function() {
// Configuration of RequireJS
requirejs.config({
// No module can start with require. This can potentially allow easier definition of some elements
enforceDefine : true,
map : {
'*': {
'jquery': 'libs/jquery',
},
// To make jquery work with requireJS: see http://requirejs.org/docs/jquery.html
// 'jquery' wants the real jQuery module
// though. If this line was not here, there would
// be an unresolvable cyclic dependency.
'libs/jquery': { 'jquery': 'jquery' },
},
// The base URL is just the top-level directory where the files are stored
baseUrl : './',
// Kick-start the application by loading these files
deps : [ 'MyMainPanel' ],
});
});
我定义了一个“自定义”JQuery(在RequireJS文档中),位于/libs/jquery.js
define(['jquery'], function (jq) {
return jq.noConflict( true );
});
在maven
pom.xml
:
...
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>${jquery.version}</version>
</dependency>
...
在使用jquery的模块的instanciation中,我收到以下错误:
GET http://localhost:8080/jquery.js 404 (Not Found)
require.js:166 Uncaught Error: Script error for: jquery
http://requirejs.org/docs/errors.html#scripterror
使用JQuery的模块如下:
define(['ractive',
'jquery',
function(Ractive,
$,
){
var Panel = Ractive.extend({
el:"mainPanel",
oninit: function(){
$.ajax({url: "/myURL"}).done(function(types){
// Work
})
}
})
return Panel
})
答案 0 :(得分:0)
我找到的唯一解决方案(解决方法)是使用“强制定义”值:
requirejs.config({
enforceDefine : false,
map : {
'libs/jquery' : {
'jquery' : "webjars/jquery/${jquery.version}/jquery"
},
'*': {
'jquery' : 'libs/jquery',
},
},
baseUrl : './',
deps : [ 'MyMainPanel' ],
});
我不知道它为什么会起作用,但它确实有效。我会坚持下去,直到找到更好的解决方案。