Per caricare un main.jsfile personalizzato su tutte le pagine (nel modo RequireJS) questo è un buon modo:
1) Crea main.js
Crea main.jsall'interno della cartella del tema
<theme_dir>/web/js/main.js
con questo contenuto:
define([
"jquery"
],
function($) {
"use strict";
// Here your custom code...
console.log('Hola');
});
In breve : dichiariamo le dipendenze all'inizio, ad es "jquery". Definiamo come parametro della funzione il nome della variabile per l'utilizzo della dipendenza all'interno della funzione, ad es "jquery" --> $. Inseriamo tutto il nostro codice personalizzato all'interno function($) { ... }.
2) Dichiarare main.jscon un requirejs-config.jsfile
Crea un requirejs-config.jsfile nella cartella del tema:
<theme_dir>/requirejs-config.js
con questo contenuto:
var config = {
// When load 'requirejs' always load the following files also
deps: [
"js/main"
]
};
"js/main"è il percorso verso la nostra abitudine main.js. L'estensione ".js" non è richiesta.
La nostra requirejs-config.jssarà unita ad altre requirejs-config.jsdefinite in Magento.
RequireJS caricherà il nostro main.jsfile, su ogni pagina, risolvendo le dipendenze e caricando i file in modo asincrono.
Opzionale: Inclusa libreria di terze parti
Questo è il modo di includere librerie di terze parti.
1) Aggiungi la libreria in web/js:
<theme_dir>/web/js/vendor/jquery/slick.min.js
2) Apri requirejs-config.jse aggiungi questo contenuto:
var config = {
deps: [
"js/main"
],
// Paths defines associations from library name (used to include the library,
// for example when using "define") and the library file path.
paths: {
'slick': 'js/vendor/jquery/slick.min',
},
// Shim: when you're loading your dependencies, requirejs loads them all
// concurrently. You need to set up a shim to tell requirejs that the library
// (e.g. a jQuery plugin) depends on another already being loaded (e.g. depends
// on jQuery).
// Exports: if the library is not AMD aware, you need to tell requirejs what
// to look for so it knows the script has loaded correctly. You can do this with an
// "exports" entry in your shim. The value must be a variable defined within
// the library.
shim: {
'slick': {
deps: ['jquery'],
exports: 'jQuery.fn.slick',
}
}
};
Sembra più complicato di quello che è in realtà.
3) Aggiungi la dipendenza all'interno di main.js:
define([
'jquery',
'slick'
],
function($) {
// ...
});