JavaScript
Import / Export
CommonJS require()
เรียนรู้ CommonJS require() — ระบบ module ของ Node.js สำหรับ import ค่าจาก module อื่น
CommonJS คืออะไร — ระบบ module ของ Node.js
JavaScript มีระบบ module หลัก 2 ระบบ: - **CommonJS** — ระบบดั้งเดิมของ **Node.js** ใช้ `require()` และ `module.exports` - **ES Module** — ระบบมาตรฐานใหม่ ใช้ `import` และ `export` (เรียนในบท import-module) CommonJS เป็นระบบที่ Node.js ใช้มาตั้งแต่แรก — **ไม่สามารถใช้ในเบราว์เซอร์โดยตรงได้** ต้องใช้ Node.js รัน ในบทนี้เราจะเรียนวิธี **import** แบบ CommonJS ด้วย `require()` **ก่อนเริ่ม:** ตรวจสอบว่าคุณมี Node.js ติดตั้งอยู่แล้วหรือยัง — เปิด terminal แล้วรัน `node -v` ถ้าเห็นเลขเวอร์ชันแสดงว่าพร้อมแล้ว
// ❌ ก่อน — ทุกอย่างอยู่ในไฟล์เดียว
// app.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
// ฟังก์ชันทุกตัวปนอยู่ในไฟล์เดียว — ใช้ซ้ำไม่ได้
// ✅ หลัง — CommonJS module
// math.js — module ที่ export ไว้ให้
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
const PI = 3.14159;
module.exports = { add, multiply, PI };
// main.js — require เข้ามาใช้
const { add, multiply, PI } = require('./math.js');
console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
console.log(PI); // 3.14159- **CommonJS** — ระบบ module ของ Node.js — ใช้ `require()` import, `module.exports` export
- **ES Module** — ระบบมาตรฐานใหม่ — ใช้ `import`/`export` (คนละบท)
- **`require()`** — ฟังก์ชันที่ Node.js จัดให้ — import ค่าจาก module อื่น
- **`module.exports`** — object ที่กำหนดว่าอะไรให้ import ได้ — (เรียนในบท export-common)
require() พื้นฐาน — const mod = require('./file')
รูปแบบพื้นฐานของ `require()`: `const ชื่อ = require('./path/to/file');` `require()` จะ return ค่า `module.exports` ของ module นั้น — ถ้า module export object ก็ได้ object, export function ก็ได้ function, export string ก็ได้ string
// math.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
const PI = 3.14159;
module.exports = { add, multiply, PI };
// main.js — require ทั้ง module
const math = require('./math.js');
// เข้าถึงผ่าน object
console.log(math.add(5, 3)); // 8
console.log(math.multiply(4, 2)); // 8
console.log(math.PI); // 3.14159// greet.js
function greet(name) {
return "สวัสดี " + name;
}
module.exports = greet;
// main.js — require ได้ function ตรง ๆ
const greet = require('./greet.js');
console.log(greet("Alice")); // "สวัสดี Alice"- `require('./path/file')` — import ค่าที่ module นั้น export ไว้
- Path ต้องเป็น relative path — `./file.js` หรือ `../folder/file.js`
- `.js` อาจละได้ใน Node.js — `require('./math')` ก็ใช้ได้
- `require()` return ค่า `module.exports` — object, function, หรืออะไรก็ตามที่ถูก export
destructuring require — const { x, y } = require('./file')
เมื่อ module export object ที่มีหลาย key — คุณสามารถใช้ **destructuring** เพื่อเลือกเฉพาะ key ที่ต้องการ: `const { name1, name2 } = require('./file.js');` แบบนี้กระชับกว่าใช้ `math.add()` ทุกครั้ง
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
const PI = 3.14159;
module.exports = { add, subtract, multiply, PI };
// main.js — destructuring เลือกเฉพาะที่ต้องการ
const { add, PI } = require('./math.js');
console.log(add(5, 3)); // 8
console.log(PI); // 3.14159
// subtract, multiply ไม่ได้ถูก import — ใช้ไม่ได้// math.js
module.exports = {
add: function(a, b) { return a + b; },
PI: 3.14159
};
// main.js — destructuring เปลี่ยนชื่อได้
const { add: sum, PI: piValue } = require('./math.js');
console.log(sum(5, 3)); // 8
console.log(piValue); // 3.14159- `const { name } = require()` — destructuring เลือกเฉพาะ key ที่ต้องการ
- `const { oldName: newName } = require()` — เปลี่ยนชื่อตอน destructuring
- เลือกเฉพาะที่ต้องใช้ — ไม่ต้อง require ทั้ง module ถ้าใช้แค่บางตัว
- ชื่อต้องตรงกับ key ใน `module.exports` — case-sensitive
require vs import — ข้อแตกต่างสำคัญ
`require()` (CommonJS) กับ `import` (ES Module) มีความแตกต่างที่ต้องรู้: - **require** — import แบบ **sync** (รันทันที, blocking) — ใช้ใน Node.js — `.js` ละได้ - **import** — import แบบ **async** (ไม่ blocking) — ใช้ใน browser + Node.js (เวอร์ชันใหม่) — ต้อง `.js` - **require** — ใช้ `module.exports` ฝั่ง export - **import** — ใช้ `export` ฝั่ง export
| คุณสมบัติ | CommonJS (require) | ES Module (import) |
|---|---|---|
| ใช้ใน | Node.js | Browser + Node.js |
| การทำงาน | Sync (blocking) | Async (non-blocking) |
| syntax import | `const x = require('./f')` | `import { x } from './f.js'` |
| syntax export | `module.exports = {}` | `export { }` / `export function` |
| `.js` ละได้? | ละได้ | ห้ามละ — ต้องใส่ `.js` |
| รองรับ destructuring | ได้ — `const { x } = require()` | ไม่มี destructuring syntax โดยตรง ใช้ `import { x } from` |
| อยู่ใน top-level เท่านั้น? | ใช้ที่ไหนก็ได้ — ข้างใน if, function | เฉพาะ top-level (ยกเว้น dynamic import) |
**สำคัญ:** CommonJS กับ ES Module ใช้ร่วมกันในไฟล์เดียวกันไม่ได้: - ถ้าไฟล์ใช้ `import` → ห้ามใช้ `require()` - ถ้าไฟล์ใช้ `require()` → ห้ามใช้ `import` - Node.js รองรับทั้ง 2 ระบบ — แต่ต้องเลือกใช้อย่างใดอย่างหนึ่งต่อ 1 ไฟล์
วิธีรัน — ใช้ node ไม่ใช่ browser
CommonJS รันใน **browser ไม่ได้** — ต้องใช้ Node.js วิธีรัน: 1. สร้างไฟล์ `.js` ในโปรเจกต์ 2. เปิด terminal / command prompt 3. ใช้คำสั่ง: `node main.js` ```bash $ node main.js 8 3.14159 ``` **สำคัญ:** ห้ามใช้ Live Server หรือเปิดไฟล์ตรง ๆ — `require()` ไม่ถูกรู้จักใน browser
# 1. cd เข้า folder โปรเจกต์
cd my-project
# 2. รันไฟล์ main.js
node main.js
# 3. ดูผลลัพธ์ใน terminal (ไม่ใช่ browser console)
# 8
# 3.14159- **Node.js เท่านั้น** — CommonJS ใช้ใน browser ไม่ได้
- **`node ชื่อไฟล์.js`** — รันใน terminal
- **ผลลัพธ์ออกใน terminal** — ไม่ใช่ browser console
- **Live Server ไม่เกี่ยว** — Live Server ใช้กับ ES modules เท่านั้น
ข้อควรระวังและความเข้าใจผิดที่พบบ่อย
มือใหม่ที่เริ่มใช้ `require()` มักสับสนระหว่าง CommonJS กับ ES module — มาดูเรื่องที่พบบ่อยและวิธีแก้:
| เรื่องที่เข้าใจผิด / ทำผิด | สิ่งที่เกิดขึ้นจริง | วิธีแก้ |
|---|---|---|
| ใช้ `require()` ใน browser (HTML `<script>`) | `ReferenceError: require is not defined` | CommonJS ใช้ใน browser ไม่ได้ — ต้องใช้ Node.js หรือเปลี่ยนเป็น `import` + `<script type='module'>` |
| ใช้ `require()` แล้ว path ผิด (`require('./math')` — ไฟล์ชื่อ math แต่มันหมายถึง math.js) | `Error: Cannot find module './math'` | ตรวจสอบ path และชื่อไฟล์ — `.js` อาจละได้ใน Node.js แต่ต้องเป็น path ที่ถูกต้อง |
| เขียน `require()` กับ `import` ในไฟล์เดียวกัน | `SyntaxError: Cannot use import statement outside a module` หรือ `require is not defined` | เลือกใช้ระบบเดียวต่อไฟล์ — `require()` หรือ `import` ไม่ใช่ทั้งคู่ |
| destructuring ผิด key — ใช้ชื่อที่ module ไม่ได้ export | ค่าที่ได้จะเป็น `undefined` — ไม่ error | ตรวจสอบ key ใน `module.exports` — ตัวเล็กตัวใหญ่ต้องตรงกัน |
| ใช้ `require()` ใน ES module file (ไฟล์ที่ตั้ง `.mjs` หรือมี `"type": "module"` ใน package.json) | `ReferenceError: require is not defined in ES module scope` | ใน ES module scope ต้องใช้ `import` — ไม่ใช่ `require()` |
// ❌ require ใน browser
// (ใน HTML: <script src="main.js"></script>)
const math = require('./math.js');
// ❌ ReferenceError: require is not defined
// โปรเจกต์ Node.js:
// ✅ ถูกต้อง — รันด้วย node main.js
const math = require('./math.js');
console.log(math.add(5, 3)); // 8
// ========================================
// ❌ require กับ import ในไฟล์เดียวกัน
import { add } from './math.js';
const express = require('express');
// ❌ SyntaxError
// ========================================
// ❌ destructuring ผิด key
const { Add } = require('./math.js'); // math.js export { add }
console.log(Add); // undefined — ไม่ได้ error แค่ได้ undefinedสรุป — CommonJS require()
- **`require()`** — import แบบ CommonJS — ใช้ใน **Node.js** เท่านั้น
- **`const mod = require('./file')`** — import ทั้ง module เข้า object
- **`const { x, y } = require('./file')`** — destructuring เลือกเฉพาะที่ต้องการ
- **`const { old: new } = require('./file')`** — destructuring เปลี่ยนชื่อได้
- **Sync** — `require()` รันทันที blocking — ต่างจาก `import` ที่ async
- **รันด้วย `node main.js`** — ไม่ใช่ browser ไม่ใช่ Live Server
- **CommonJS vs ES Module** — คนละระบบ ใช้ร่วมกันในไฟล์เดียวกันไม่ได้
| สิ่งที่อยากรู้ | คำตอบสั้น |
|---|---|
| require syntax | `const mod = require('./file.js')` |
| destructuring | `const { x, y } = require('./file.js')` |
| ใช้ใน browser? | ไม่ — `require is not defined` |
| ใช้ใน Node.js? | ใช่ — `node main.js` |
| export ของ CommonJS คืออะไร | `module.exports = { }` — เรียนบท export-common |
ลองทำ — ใช้ require() กับ Node.js
ถึงเวลาลองใช้ `require()` ด้วยตัวเองแล้ว! เราจะสร้าง project เล็ก ๆ ประกอบด้วย **2 ไฟล์**: 1. **`math.js`** — module ที่ export ฟังก์ชันคำนวณ 2. **`main.js`** — ไฟล์หลักที่ require ฟังก์ชันจาก `math.js` มาใช้ เปิด editor ของคุณ สร้าง folder ใหม่ (ตั้งชื่ออะไรก็ได้ เช่น `my-commonjs-import`) แล้วสร้างไฟล์ตามด้านล่าง
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
const PI = 3.14159;
module.exports = { add, subtract, multiply, PI };// main.js — require ฟังก์ชันจาก math.js
// แบบที่ 1: require ทั้ง module
const math = require('./math.js');
console.log("=== require ทั้ง module ===");
console.log("5 + 3 =", math.add(5, 3));
console.log("PI =", math.PI);
// แบบที่ 2: destructuring เลือกเฉพาะที่ต้องการ
const { subtract, multiply } = require('./math.js');
console.log("\n=== destructuring ===");
console.log("10 - 5 =", subtract(10, 5));
console.log("7 × 6 =", multiply(7, 6));
// แบบที่ 3: destructuring เปลี่ยนชื่อ
const { PI: piValue, add: sum } = require('./math.js');
console.log("\n=== destructuring + rename ===");
console.log("PI =", piValue);
console.log("3 + 4 =", sum(3, 4));ไฟล์ทั้ง 2 ต้องอยู่ใน **folder เดียวกัน** โครงสร้างจะเป็นแบบนี้: ``` my-commonjs-import/ ├── math.js └── main.js ``` **วิธีรัน**: เปิด terminal → cd เข้า folder → รัน: ```bash node main.js ``` ⚠️ ห้ามเปิดไฟล์ใน browser — CommonJS ใช้ใน browser ไม่ได้ ต้องใช้ Node.js เท่านั้น
=== require ทั้ง module ===
5 + 3 = 8
PI = 3.14159
=== destructuring ===
10 - 5 = 5
7 × 6 = 42
=== destructuring + rename ===
PI = 3.14159
3 + 4 = 7- ถ้า terminal **ไม่แสดงอะไรเลย** → เช็คว่า `console.log` อยู่ใน `main.js` และรันด้วย `node main.js` ถูกไหม
- ถ้า terminal **Error: Cannot find module** → ตรวจสอบ path — ต้องมี `./` นำหน้า หรือชื่อไฟล์ไม่ตรง
- ถ้า terminal **ReferenceError: require is not defined** → อย่าเปิดใน browser — ใช้ `node` ใน terminal
- ถ้าเห็นผลลัพธ์ครบตามด้านบน → **ผ่านแล้ว!** require() ทำงานถูกต้อง
เห็นผลลัพธ์ครบแล้ว? ลอง **ทดลองเปลี่ยนโค้ด** เพื่อทำความเข้าใจให้ลึกขึ้น: - ใน `main.js` ลอง **ใช้ destructuring ผิด key** — เปลี่ยน `PI` เป็น `pi` (ตัวเล็ก) แล้วดูผลลัพธ์ (จะได้ `undefined`) - ใน `main.js` ลอง **require โดยไม่ใช้ `./`** — เปลี่ยน `'./math.js'` เป็น `'math.js'` แล้วดู error - ใน `math.js` ลอง **เปลี่ยนจาก `module.exports` เป็น `exports`** — เปลี่ยนเป็น `exports.add = add;` แล้วดูว่า main.js ยังทำงานได้ไหม - ลอง **เพิ่มฟังก์ชันใหม่** ใน `math.js` แล้ว require มาใช้ เห็น error แล้วจำไว้ — การ require ที่ถูกต้องเป็นทักษะสำคัญสำหรับการทำงานกับ Node.js