Magento 2: How to call js Function that is in my Require.js file from phtml file

Magento 2: How to call js Function that is in my Require.js file from phtml file

July 16, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento 2: How to call js Function that is in my Require.js file from phtml file

Solving JavaScript Function Globalization Issues in Magento 2

When working with Require.js in Magento 2, you may encounter challenges when trying to access functions from your Require.js module within the phtml files. This is because by default, functions defined inside a Require.js module are not global by nature.

The Problem: Functions Are Not Global

In your example, the initMap function is defined as a local scope inside the main module wrapper function. As a result, it is not accessible globally from other JavaScript files or phtml templates in Magento 2.

Here’s your current configuration:

// gslmap.js
define([
  'jquery'
], function ($) {

  return function (config) {
    console.log(config);
  }

  function initMap() {
    console.log('initMap is being called');
  }
});

The initMap function is defined locally inside the module, and it’s not reachable from other files.

The Solution: Expose the Function

To make a function global so that you can call it from phtml or other JavaScript files, you need to expose it as part of your returned object from the module. This exposes the function to the global scope while keeping the rest of your code encapsulated.

Update your gslmap.js file like this:

// gslmap.js
define([
  'jquery'
], function ($) {

  return {
    initMap: function (config) {
      console.log('initMap is being called');
    }
  }

});

Now, the initMap function has been exposed as a property of the returned object. This allows it to be accessed globally.

Calling the Global Function from phtml

To use this global function in your phtml file:

// Your phtml file
<script>
    require(['Gauge_StoreLocator/js/app'], function (gslMap) {
        gslMap.initMap();
    });
</script>

Here, we’re using Require.js to load the Gauge_StoreLocator/js/app module and then calling its exposed initMap function.

Conclusion

Remember that functions inside a Require.js module are local by default. To use them outside of the module, you must expose them as properties of the returned object or use AMD’s define() method with the ‘exports’ parameter to make your entire module global.

This approach ensures that your code remains modular and only exposes what is necessary, keeping your JavaScript application clean and maintainable in Magento 2.

Magento 2 Database API Extensions

Our network