Module là một hoặc nhiều hàm hay lớp đối tượng cùng thực hiện một nhiệm vụ. Do các hàm hay lớp có cùng chức năng được đặt trong một file, nên ta có thể xem một module như là một file thông thường.
Code ở trong một module luôn ở strict mode.
Import and Export
Ví dụ ta có file app.js có hàm tính tổng hai số:
// app.js
const sum = (a, b) => a + bTa có một file khác có tên là main.js, và chúng ta muốn sử dụng hàm sum() có ở bên file app.js. Để có thể sử dụng, ta cần:
- Module hóa file
main.jsbằng cách thêm attributetype = "module"vào dòng<script src="main.js"></script>. - Export hàm
sum()ở fileapp.js. - Import hàm
sum()ở filemain.js.
Giả sử app.js và main.js cùng cấp trong cây thư mục thì ta thực hiện những bước trên như sau:
// app.js
const sum = (a, b) => a + b
export default sum// main.js
import sum from "./app.js"Có thể đổi tên hàm sum bằng từ khóa as:
// main.js
import sum as sumOfNumbers from "./app.js"Khi log import này ra console, ta sẽ được đoạn code của hàm sum:

Important
Lưu ý là một file JS chỉ có duy nhất một default export. Dù vậy, một export có thể bao gồm nhiều biến hoặc hàm, được đóng gói trong dấu ngoặc kép như một object.
Import with Destructuring
Giả sử ta export nhiều biến từ file app.js:
// app.js
export const pi = 3.14
export const g = 9.8Khi import vào file main.js, có thể sử dụng destructuring:
// main.js
import { pi, g } from "./app.js"Để có thể import tất cả trong một object, ta sử dụng toán tử *:
// main.js
import * as math from "./app.js"Bằng cách này, ta có thể lấy tất cả các export cho vào math. Biến math này là một object thuộc lớp đối tượng Module.

Export From Other Module
Ta đã export hàm sum từ file app.js. Giờ ta có thêm một file khác là index.js nằm cùng cấp với file app.js trong một thư mục:
+-- js
| +-- app.js
| +-- index.js
+-- index.html
+-- main.jsFile index.js có thể export hàm sum của file app.js
// index.js
export { default } from "./app.js"Đoạn code tương đương:
// index.js
import sum from "./app.js"
export default sumFile main.js import từ default của app.js thông qua index.js làm trung gian:
// main.js
import sum from "./js/index.js"Nếu muốn index.js không export default, ta có thể dùng từ khóa as kèm theo tên mới:
// index.js
export { default as sum2 } from "./app.js"Code ở main.js trở thành:
// main.js
import { sum2 } from "./js/index.js"