Aby załadować main.jsplik niestandardowy na wszystkie strony (w sposób RequireJS), jest to dobry sposób:
1) Utwórz main.js
Utwórz main.jsw folderze motywu
<theme_dir>/web/js/main.js
z tą zawartością:
define([
"jquery"
],
function($) {
"use strict";
// Here your custom code...
console.log('Hola');
});
W skrócie : deklarujemy zależności na początku, np "jquery". Jako parametr funkcji definiujemy nazwę zmiennej do wykorzystania zależności w funkcji, np "jquery" --> $. Umieszczamy w nim cały nasz niestandardowy kod function($) { ... }.
2) Zadeklaruj main.jsza pomocą requirejs-config.jspliku
Utwórz requirejs-config.jsplik w folderze motywu:
<theme_dir>/requirejs-config.js
z tą zawartością:
var config = {
// When load 'requirejs' always load the following files also
deps: [
"js/main"
]
};
"js/main"jest ścieżką do naszego zwyczaju main.js. Rozszerzenie „.js” nie jest wymagane.
Nasze requirejs-config.jszostaną połączone z innymi requirejs-config.jszdefiniowanymi w Magento.
RequireJS załaduje nasz main.jsplik na każdej stronie, rozwiązując zależności i ładując pliki w sposób asynchroniczny.
Opcjonalnie: w tym biblioteka innej firmy
W ten sposób można włączyć biblioteki stron trzecich.
1) Dodaj bibliotekę w web/js:
<theme_dir>/web/js/vendor/jquery/slick.min.js
2) Otwórz requirejs-config.jsi dodaj tę treść:
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',
}
}
};
Wygląda na bardziej skomplikowane niż w rzeczywistości.
3) Dodaj zależność w ramach main.js:
define([
'jquery',
'slick'
],
function($) {
// ...
});