通过require引用的一个外部JavaScript文件和require.js有冲突
通过require引用的一个外部JavaScript文件和require.js有冲突
想问一下大佬,一个前端页面需要引用一个外部JavaScript文件,在web/view下的JS文件里加入了下面的代码,这个api.js文件已经被正确引用到页面上,但是这个api.js里面中间一段用的RSVP的库(RSVP这个库用了define函数啥的),所以中间这段JS代码就没有执行成功。
require(['https://www.sample.com/api.js'], function (){});
但是如果改M2的核心代码把这个api.js 文件在require.js之前用普通的<script>标签来引用到的话就没有问题了,所以我想问一下有什么办法在插件的这个前端页面在require.js加载这个api.js文件吗
1,在require-config.js里定义customjs这个js模块
<?php if ($mode == "production") {
$url = "https://abc.production/payment.js";
} else {
$url = "https://abc.sandbox/payment.js";
} ?>
// $url is customized JS url
<script>
require.config({
map: {
'*': {
'customjs': '<?php echo $url ?>'
}
}
});
</script>
2,在js里或者模版里 调用customjs这个js模块
/*browser:true*/
/*global define*/
define(
[
'ko',
'jquery',
'Magento_Checkout/js/view/payment/default',
'Magento_Checkout/js/model/quote',
'customjs' // here the js file is mapped
],
function (
ko,
$,
Component,
quote,
custom // you can refer this object to use customjs functions
) {
'use strict';
...........
// and you can call your customjs functions easily
.........
});
参考
https://webkul.com/blog/call-configurable-external-js-url-magento2/
