How to call a configurable external JS URL in magento2
Today I will explain in this article, that how you can create a configurable JS external URL and then map it with another js in magento 2. Suppose you stuck in a condition, i.e. you have to call only one JS with some conditions, like if mode is production then ABC.js should call and if mode is desug then XYZ.js should call , so this blog will be very helpful for you. So lets get started. At first you will need to call a template file on your page, i.e. test.phtml. In this file write the configurable JS url, for e.g. :
<?php if ($mode == "production") {
$url = "https://abc.production/payment.js";
} else {
$url = "https://abc.sandbox/payment.js";
} ?>
// $url :- You can use any external js url
<script>
require.config({
map: {
'*': {
'customjs': '<?= $url ?>'
}
}
});
</script>
Whenever test.phtml is executed, the above code will make an entry to requirejs-config.js file. Now how do you call this in your other JS files? You have to add the below code after the above code in the same file to call another js.
<script type="text/x-magento-init">
{
"*": {
"newcustomjs":{}
}
}
</script>
So let’s have a look below in your other newcustomjs.js file.
/*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
.........
});
Now when newcustomjs.js is called then only your customjs file is invoked. Hope this blog will help you to build applications in your module in a better way. Try this and if you have any queries then just comment below 🙂
Be the first to comment.