export default 와 export 차이

김태훈·2023년 4월 3일
0

https://medium.com/@etherealm/named-export-vs-default-export-in-es6-affb483a0910 export 문법 관련
https://www.codingem.com/javascript-semicolon-usage/ 세미콜론 관련
참조

서론

당연히 Node.js에서 import export를 쓰려면,
Node.js는 COMMON JS 기반이므로, ES5~ 문법으로 바꿔주어야만 import와 export를 사용할 수 있다.
따라서 package.json 파일에

"type":"module"

을 추가한다.

별도의 주의사항

export 와 import를 통해 함수와 클래스를 내보낼 때, 웬만하면 뒤에 세미콜론을 붙이기 않기로 하자.

  • ' } ' 로 끝날 때 세미콜론 쓰지 않기
  • ' ) ' 로 끝날 때 세미콜론 쓰지 않기
  • while, switch, if 문은 당연히 쓰지 않기

export

1. export default declaration

선언부 앞에 export 하는 경우

export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// 상수 내보내기
export const MODULES_BECAME_STANDARD_YEAR = 2015;

// 클래스 내보내기
export class User {
  constructor(name) {
    this.name = name;
  }
}

2. export apart from declaration

function sayHi(user) {
  alert(`Hello, ${user}!`);
}

function sayBye(user) {
  alert(`Bye, ${user}!`);
}

export {sayHi, sayBye}; // 두 함수를 내보냄

import

1. import 로 모듈 이름 불러오기

import {sayHi} from '/say.js';

2. import 모듈을 다른 이름으로 바꾸기 (alias)

import {sayHi as Hi} from '/say.js';

export도 동일하게 가능

3. import 전체(*)를 alias 로 활용해서 불러오기

import * as say from './say.js';

export default

1. 모듈이 library 나 module을 포함한 경우

2. single entity로써 해당 entity 하나에 많은 기능이 포함된 경우 -> 더 선호됨

Modules provide a special export default (“the default export”) syntax to make the “one thing per module” way look better.
해당 공식 문서

1. export

export default class User { // just add "default"
  constructor(name) {
    this.name = name;
  }
}

2. import

import User from './user.js'; // not {User}, just User

new User('John');

Named Export와 Export Default 의 차이

Named ExportExport Default
export class User {...}export default class User {...}
import {User} from ...import User from ...

1. export default

이 경우에, 보통은 '한가지 모듈'만 내보내는 경우이다.
따라서, 굳이 name을 붙이지 않아도 되고,
import할 때 이름을 클라이언트 마음대로 바꿀 수 있다.

2. export 만 쓴 경우

반드시 이름을 붙일 것.
import도 export한 모듈 이름 그대로 해와야 한다.

Named Export 와 Export Default를 섞어 쓴 경우

  • export
//export
export default class User {
  constructor(name) {
    this.name = name;
  }
}

export function sayHi(user) {
  alert(`Hello, ${user}!`);
}
  • import
//import
import {default as User, sayHi} from './user.js';

new User('John');

모듈을 가져와서 다시 내보낼 수도 있다.

profile
기록하고, 공유합시다

0개의 댓글