I am creating a custom module which retrieves the image from Package_Module/images/image.jpg in my javascript code. How to get the require js base URL or Static URL? or do you have any suggestions on what is the best to get the link of an image asset from javascript level?
Asked
Active
Viewed 2,440 times
2
Ner
- 1,071
- 12
- 28
-
2Possible duplicate of How to get site url inside javascript file? – Ben Crook Aug 01 '18 at 08:19
-
@BenCrook base URL and require js base URL might not be the same. :) – Ner Aug 01 '18 at 08:23
-
If the base URL differs between files that is a problem IMO, the base URL should always be the base URL. – Ben Crook Aug 01 '18 at 10:05
-
I've added a method to get the pub/static URL including your vendor, theme and locale. It sounds like that may be what you're after when you say the require JS base URL isn't the same? – Ben Crook Aug 01 '18 at 10:11
-
1Hi @BenCrook, yes, that was I was after. Should I adjust the description of this question? – Ner Aug 02 '18 at 02:09
-
I think wording it as the theme static file URL may make more sense, I understand base URL to be the domain only such as https://example.com. – Ben Crook Aug 02 '18 at 10:14
2 Answers
6
You can pass it through using x-magento-init as Khoa mentioned, or you can use this:
require.toUrl('test');
Which will output:
//localhost:3000/static/frontend/Vendor/theme/en_GB/test
Where localhost:3000 is your base URL.
Ben Crook
- 15,685
- 3
- 52
- 104
-2
1) Using the Js global variable. For example, on the checkout page, we can check:
window.checkoutConfig.imageData
See more here: https://magento.stackexchange.com/a/133732/33057
2) Passing the image to Js variable in your phtml:
<script type="text/x-magento-init">
{
"[data-block='minicart']": {
"Magento_Ui/js/core/app": <?= /* @escapeNotVerified */ $block->getJsLayout() ?>
},
"*": {
"Magento_Ui/js/block-loader": "<?= /* @escapeNotVerified */ $block->getViewFileUrl('images/loader-1.gif') ?>"
}
}
</script>
Khoa TruongDinh
- 32,054
- 11
- 88
- 155
