สิ่งเหล่านี้คือระบบสองโมดูลของ JavaScript สำหรับการแบ่งโค้ดไปยังหลายไฟล์
ES Modules (ESM) — มาตรฐานสมัยใหม่
js
// import / export, used in browsers and modern Node
import { sum } from ;
defaultThing ;
x = ;
() {};
สิ่งเหล่านี้คือระบบสองโมดูลของ JavaScript สำหรับการแบ่งโค้ดไปยังหลายไฟล์
// import / export, used in browsers and modern Node
import { sum } from ;
defaultThing ;
x = ;
() {};
const { sum } = require("./math");
module.exports = { x: 1 };
| ES Modules | CommonJS | |
|---|---|---|
| Syntax | import/export | require/module.exports |
| Loading | static, async | dynamic, synchronous |
| Analyzable | ✅ → tree-shaking | ❌ harder |
| Bindings | live (read-only) | ค่าที่คัดลอก |
this at top | undefined | module.exports |
Static หมายความว่า ESM imports นั้นเป็นที่รู้จักในเวลาแยกวิเคราะห์ ซึ่งให้ bundlers สามารถทำ tree-shaking (ปล่อยส่วนที่ไม่ได้ใช้งาน) CommonJS require นั้นเป็นแบบพลวัต (คุณสามารถ require แบบมีเงื่อนไข) ดังนั้นจึงไม่สามารถวิเคราะห์ได้ง่ายนัก
{ "type": "module" } // in package.json, or use the .mjs extension
คุณไม่สามารถ require() แพ็คเกจ ESM-only จาก CommonJS ได้; การผสมทั้งสองมีปัญหาด้านหลัง ESM imports ก็เป็น live bindings — หากผู้ส่งออกเปลี่ยนค่า ผู้นำเข้าจะเห็นค่าใหม่ (CJS ให้คุณสำเนา snapshot)
ESM คือปัจจุบัน (ของเบราวเซอร์โนแลท, tree-shakeable, top-level await)
จำเป็นต้องชอบมันสำหรับโค้ดใหม่; เข้าใจ CJS เพราะระบบนิเวศ Node ส่วนใหญ่ยังคงใช้งาน
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค