0

Many answers here on StackExchange and in documentation around the Internet indicate that to include a custom JavaScript file in a Magento 2 store that you should create a requirejs-config.js to specify a file alias that you will then separately reference to require it.

For example, you might have this requirejs-config.js file:

var config = {
   map: {
       '*': {
           myscript: 'My_Module/js/myscript',
       }
   }
};

And this in your PHTML:

<script type="text/javascript">
    require(['myscript'], function($) {
        // optional loaded callback here
    });
</script>

This works, but the question is:

Are both steps really necessary to include the JavaScript file?

4
  • @St3phan There are a whole lot of questions on here that are basically dups asking how to add JS. That's not the point of this question: it's a self-answered rhetorical question documenting that the requirejs-config.js isn't really needed in case others wonder that in the future. If you have the access (I don't), please remove that duplicate question suggestion from this. Oct 27, 2017 at 2:23
  • Your answer is identical, even less information than in the duplicate response.
    – St3phan
    Oct 27, 2017 at 8:19
  • @St3phan, the point here is to be direct about the question of whether requirejs-config.php is needed. Your answer on the other question implies it is needed, when it's not. Oct 27, 2017 at 12:46
  • It is explained both solutions.
    – St3phan
    Oct 27, 2017 at 12:48

1 Answer 1

1

No.

The require-config.js isn't needed. All it's doing is creating a simpler alias, so most of the time it's not worth it if your JavaScript file isn't a library that's going to be required by a lot of other code. You can just include the path to the file you're requiring directly in your call to RequireJs:

<script type="text/javascript">
    require(['My_Module/js/myscript'], function($) {
        // optional loaded callback here
    });
</script>

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