2

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?

6
  • 2
    Possible duplicate of How to get site url inside javascript file?
    – Ben Crook
    Commented Aug 1, 2018 at 8:19
  • @BenCrook base URL and require js base URL might not be the same. :)
    – Ner
    Commented Aug 1, 2018 at 8:23
  • If the base URL differs between files that is a problem IMO, the base URL should always be the base URL.
    – Ben Crook
    Commented Aug 1, 2018 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
    Commented Aug 1, 2018 at 10:11
  • 1
    Hi @BenCrook, yes, that was I was after. Should I adjust the description of this question?
    – Ner
    Commented Aug 2, 2018 at 2:09

2 Answers 2

7

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.

2
  • 1
    Perfectly, I didn't know about it +1. Commented Aug 2, 2018 at 3:50
  • Yes. This is exactly what I need. I just know. :) Thanks!
    – Ner
    Commented Aug 3, 2018 at 0:43
-2

1) Using the Js global variable. For example, on the checkout page, we can check:

window.checkoutConfig.imageData

enter image description here

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.