Junior #commonjs#require#module-cache
require() hoạt động thế nào? Module cache và resolution
⚡ Trả lời nhanh
require() resolve đường dẫn, đọc và bọc file trong function wrapper, thực thi một lần rồi lưu module.exports vào require.cache theo đường dẫn tuyệt đối. Lần gọi sau trả về cùng object đã cache, nên module hoạt động như singleton.
Quy trình require('x'): resolve (core module, đường dẫn tương đối, rồi tìm trong node_modules từ thư mục hiện tại đi lên) → load → bọc trong wrapper (exports, require, module, __filename, __dirname) → chạy → cache.
// counter.js
let n = 0;
module.exports = { inc: () => ++n };
// app.js
const a = require('./counter');
const b = require('./counter');
a.inc();
console.log(b.inc()); // 2 vì a và b là cùng một object
delete require.cache[require.resolve('./counter')]; // ép load lại
exportschỉ là tham chiếu ban đầu tớimodule.exports; gánexports = ...không có tác dụng, phải gánmodule.exports = ....- Với circular require, module nhận được object
exportschưa hoàn chỉnh tại thời điểm đó.