หากต้องการโหลดmain.jsไฟล์ที่กำหนดเองในทุกหน้า (ใน RequireJS-way) นี่เป็นวิธีที่ดี:
1) สร้าง main.js
สร้างmain.jsภายในโฟลเดอร์ชุดรูปแบบ
<theme_dir>/web/js/main.js
กับเนื้อหานี้:
define([
"jquery"
],
function($) {
"use strict";
// Here your custom code...
console.log('Hola');
});
ในระยะสั้น : "jquery"เราประกาศการอ้างอิงที่เริ่มต้นเช่น "jquery" --> $เรากำหนดเป็นพารามิเตอร์ของฟังก์ชันชื่อตัวแปรสำหรับการใช้พึ่งพาภายในฟังก์ชั่นเช่น function($) { ... }เราใส่รหัสที่กำหนดเองทั้งหมดของเราภายใน
2) ประกาศmain.jsด้วยrequirejs-config.jsไฟล์
สร้างrequirejs-config.jsไฟล์ภายในโฟลเดอร์ธีม:
<theme_dir>/requirejs-config.js
กับเนื้อหานี้:
var config = {
// When load 'requirejs' always load the following files also
deps: [
"js/main"
]
};
"js/main"main.jsเป็นเส้นทางที่จะกำหนดเองของเรา ไม่จำเป็นต้องใช้ส่วนขยาย ".js"
เราrequirejs-config.jsจะถูกรวมเข้ากับสิ่งอื่นที่requirejs-config.jsกำหนดไว้ใน Magento
RequireJS จะโหลดmain.jsไฟล์ของเราในแต่ละหน้าการแก้ไขการขึ้นต่อกันและการโหลดไฟล์แบบ async
ทางเลือก: รวมถึงห้องสมุดบุคคลที่สาม
นี่เป็นวิธีรวมไลบรารีของบุคคลที่สาม
1)เพิ่มห้องสมุดในweb/js:
<theme_dir>/web/js/vendor/jquery/slick.min.js
2)เปิดrequirejs-config.jsและเพิ่มเนื้อหานี้:
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',
}
}
};
มันดูซับซ้อนกว่าที่เป็นจริง
3)เพิ่มการพึ่งพาภายในmain.js:
define([
'jquery',
'slick'
],
function($) {
// ...
});