Source: How to include and use custom js file with require js in magento2.
Source: Four Ways to Add JavaScript to Magento 2.
En-dehors d’un thème, en créant un module
Se référer à la documentation officielle de Magento 2 pour voir comment créer un nouveau module. Dans mon exemple, le vendor s’appelle Naked
et le module s’appelle HelloWorld
.
Dans app/code/Naked/HelloWorld/
créer une arborescence de dossiers et les trois fichiers suivants:
view/frontend/requirejs-config.js
view/frontend/web/js/hello-world.js
view/frontend/web/js/methods.js
view/frontend/requirejs-config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var config = { // You can also set the map property and define the prefixes for various modules. // In future, we can use these prefixes to connect the required JS modules in other modules. map: { '*': { helloWorld: 'Naked_HelloWorld/js/hello-world', methods: 'Naked_HelloWorld/js/methods', } }, // In this case, the scripts we have connected will work on all pages of the module. // Usually, some third-party libraries are connected in this way. deps: [ 'Naked_HelloWorld/js/hello-world', ] }; |
Les scripts déclarés sous la variable deps
vont fonctionner immédiatement et sur toutes les pages du site. Inutile d’initialiser quoi que ce soit dans un fichier *.phtml
.
view/frontend/web/js/hello-world.js
1 2 3 4 5 6 7 8 9 10 |
define(['jquery', 'methods'], function($, methods) { "use strict"; console.log('hello world!'); $('a.logo').on('click', function(e){ e.preventDefault(); methods.showAlert('Logo clicked!'); }); }); |
view/frontend/web/js/methods.js
1 2 3 4 5 6 7 8 9 10 11 |
define(['jquery'], function($) { var methods = {}; methods.showAlert = function(arg) { alert(arg); } return methods; }); |