How to passing Dynamic arguments from template to RequireJs in magento 2?

Magento template support script tag with X-MAGENTO-INIT declaration. You can pass dynamic PHP values to Javascript from a template file.

create demo.phtml file in your module to pass dynamic PHP value to Javascript,

<?php declare(strict_types=1);
/** Demo template file */
<script type="text/x-magento-init">
        "*": {
            "Jesadiya_Blog/js/requirejs-example" : {
                "baseUrl" : "<?= $block->escapeJs($block->getBaseUrl()); ?>",
		"storeId" : "<?= $block->escapeJs($block->getStoreId()); ?>",

Now We can fetch Base Url and Store Id in javascript file using require js. We have to create requirejs-example.js file to get both of the dynamic values.


define(function () {
    'use strict';

    return function (config, element) {
        console.log(config.baseUrl); //get Base URL
        console.log(config.storeId); // get store ID
        console.log(element); // get DOM object if element is provided while declaration of require js file.

We have passed the argument as config for the function.

Always return function takes two optional parameters.

The first parameter contains the configuration value which we have passed from the phtml.
The second parameter contains the DOM node element.

You can get store id and baseURL in javascript using the above way.