[英]How do I configure a date picker with third party js dependencies using Require JS?
我正在尝试在应用程序中使用以下“ 日期范围选择器” :通过将脚本放置在页面的head
部分中,我能够成功使其工作:但是,我不确定如何使用Require JS
进行设置。第三方依赖性。
例如:要使用JQuery UI Date Picker
我只需执行以下操作:
require.config({
paths: {
jquery: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery',
'jquery-ui': 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui'
}
});
然后像这样实例化:
require(['jquery', 'jquery-ui'], function ($) {
$(function() {
$( "#datepicker" ).datepicker();
});
});
但是,如果还有其他第三方脚本,那么我不确定如何配置它:
具体来说,有我正在努力的moment.js
和daterangepicker-master/jquery.comiseo.daterangepicker.js
依赖项。
这是有关JSFiddle的完整工作示例 :
如何使用Require JS
进行设置?
您应该查看每个库中是否都包含“ amd”一词。 例如,在第9个字符串的momentjs中,您可以看到:
typeof define === 'function' && define.amd ? define(factory) :
这意味着您可以将其包含在requirejs配置的路径部分中。 但是,如果您查看库中的内容而该词不存在,则应在配置中使用shim 。 对于您的情况,它将:
require.config({
paths: {
jquery: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery',
'jquery-ui': 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui'
"momentjs":"//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"
//shim
"daterangepicker":"//tamble.github.io/jquery-ui-daterangepicker/daterangepicker-master/jquery.comiseo.daterangepicker"
},
shim:{
"daterangepicker":{
deps:["jquery-ui","momentjs"]
}
}
}
});
因为daterangepicker具有jquery-ui作为依赖项:
shim:{
"daterangepicker":{
deps:["jquery-ui","momentjs"]
}
}
和jquery-ui依赖于第10个字符串的jquery:
define(["jquery"], factory);
那么您只能将 “ jquery-ui”作为daterangepicker的依赖项。 因此结果将是:
require.config({
paths: {
jquery: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery',
'jquery-ui': 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui',
momentjs: "//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment",
//shim
daterangepicker: "//tamble.github.io/jquery-ui- daterangepicker/daterangepicker-master/jquery.comiseo.daterangepicker"
},
shim: {
daterangepicker: {
deps: ["jquery-ui", "momentjs"]
}
}
});
require(['jquery','daterangepicker','momentjs'], function ($,dateRangePicker,momentjs) {
//dateRangePicker will be undefined, but it's ok.
window.moment = momentjs; //include momentjs in global scope because plugin wants it globally.
$("#e2").daterangepicker({
datepickerOptions: {
numberOfMonths: 2
}
});
});
index.html的:
<html>
<head>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css"/>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" />
<link rel="stylesheet" href="//tamble.github.io/jquery-ui-daterangepicker/daterangepicker-master/jquery.comiseo.daterangepicker.css" />
</head>
<body>
<script data-main="app.js" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"> </script>
<input id="e2"></input>
</body>
我做了测试,它的工作原理:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.