export/import
#HelloFrontend #HelloErmine #HelloWorld2021
export/import คืออะไร ?
คือ statement ที่ใช้เพื่อแบ่งปัน code ระหว่างไฟล์ JavaScript
ใช้งานอย่างไร ?
รูปแบบการใช้งานที่พบได้บ่อยจะมีอยู่ 2 แบบ คือ
1. Named export/import
import ต้องใช้ชื่อเดียวกันกับตอน export
import ต้องอยู่ภายใน { }
// fileA.js
export const name = "Peepee";
export const age = 12;
// fileB.js
import { name, age } from "./fileA.js";
2. Default export/import
export default ได้แค่ครั้งเดียวในแต่ละ module
import ใช้ชื่อเป็นอะไรก็ได้
// fileA.js
const name = "Peepee";
export default name;
// fileB.js
import nameOrSomething from "./fileA.js";
// fileA.js
const name = "Peepee";
export default name;
export const age = 12;
// fileB.js
import nameOrSomething, { age } from "./fileA.js";
แหล่งอ้างอิง
Last updated
Was this helpful?