DEV Community

hambalee
hambalee

Posted on

JavaScript Import Export คืออะไร ใช้ยังไง (JavaScript เบื้องต้น สำหรับมือใหม่)

Import Export ในภาษา JavaScript มีไว้ใช้สำหรับนำเข้าโค้ดจากไฟล์อื่น
เพื่อให้โค้ดจัดแบ่งเก็บไว้แยกเป็นไฟล์
เมื่อต้องการนำมาใช้ก็ Import
ตัวอย่าง

import person from './person.js'
Enter fullscreen mode Exit fullscreen mode

แต่ก่อนที่จะ Import ได้ ในไฟล์ person.js จะต้องมีการ export ด้วย

const person = {
  name: 'A'
}
export default person
Enter fullscreen mode Exit fullscreen mode

เมื่อมีการ export default แบบนี้จะเป็นการ export ทั้งหมด
สามารถ import โดยใช้ชื่อตัวแปรอื่นก็ได้

import p from './person.js'
Enter fullscreen mode Exit fullscreen mode

การ export เฉพาะบางตัวแปร
utility.js

export const a = () => {...}
export const b = 1
Enter fullscreen mode Exit fullscreen mode

ในกรณีแบบนี้เวลาจะ import ต้องเขียนแบบนี้

import { a } from './utility.js'
import { b } from './utility.js'
Enter fullscreen mode Exit fullscreen mode

ชื่อตัวแปรจะต้องเป็นชื่อเดียวกันกับชื่อตัวแปรที่ export
แต่ถ้าอยากเปลี่ยนก็สามารถทำได้

import { a as c } from './utility.js'
Enter fullscreen mode Exit fullscreen mode

หรือจะ import มาทั้งหมดก็ได้

import * as abc from './utility.js'
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)