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 하는 경우
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;
}
}
function sayHi(user) {
alert(`Hello, ${user}!`);
}
function sayBye(user) {
alert(`Bye, ${user}!`);
}
export {sayHi, sayBye}; // 두 함수를 내보냄
import {sayHi} from '/say.js';
import {sayHi as Hi} from '/say.js';
export도 동일하게 가능
import * as say from './say.js';
Modules provide a special export default (“the default export”) syntax to make the “one thing per module” way look better.
해당 공식 문서
export default class User { // just add "default"
constructor(name) {
this.name = name;
}
}
import User from './user.js'; // not {User}, just User
new User('John');
Named Export | Export Default |
---|---|
export class User {...} | export default class User {...} |
import {User} from ... | import User from ... |
이 경우에, 보통은 '한가지 모듈'만 내보내는 경우이다.
따라서, 굳이 name을 붙이지 않아도 되고,
import할 때 이름을 클라이언트 마음대로 바꿀 수 있다.
반드시 이름을 붙일 것.
import도 export한 모듈 이름 그대로 해와야 한다.
//export
export default class User {
constructor(name) {
this.name = name;
}
}
export function sayHi(user) {
alert(`Hello, ${user}!`);
}
//import
import {default as User, sayHi} from './user.js';
new User('John');