How to give alias to the require js file with requirejs-config JS magento 2?

Magento requirejs-config file provides an alias for the custom js file declared inside map or path object.

You can use an alias anywhere inside a template or other Require JS file in the Magento system.

Create a requirejs-config.js file in your module,

var config = {
    map: {
        '*': {
            homepageSlider : 'Jesadiya_Blog/js/slider'
        }
    }
}

Just consider slider.js file is available with our module and we don’t want to add the entire path in the template file to call this slider.

We have given an alias to the slider js file with homepageSlider. Now you can use an alias in any template or JS file instead of JS full path.

<?php declare(strict_types=1);
?>
<div id="content"></div>
<script type="text/x-magento-init">
    {
        "*": {
            "homepageSlider" : {
                "base_url" : "<?= $block->escapeJs($block->getBaseUrl()); ?>",
                "storeId": "<?= $block->escapeJs($block->getStoreId());?>"
            }
        }
    }
</script>

In the above template, homepageSlider will be indicated the Jesadiya_Blog/js/slider.js file.

Instead of providing an entire path of the custom js, we are fine with the alias name in the above script tag to call the JS file.


Use Case without an Alias,

You have to give the path of the JS if you haven’t declared an alias for the custom JS file.

<script type="text/x-magento-init">
    {
        "*": {
            "Jesadiya_Blog/js/slider" : {
                "base_url" : "<?= $block->escapeJs($block->getBaseUrl()); ?>",
                "storeId": "<?= $block->escapeJs($block->getStoreId());?>"
            }
        }
    }
</script>

Here we have given Jesadiya_Blog/js/slider path to call require JS file.