공부 정리/웹(Web)
JS .js 와 .mjs
경적필패.
2022. 3. 13. 20:36
반응형
공부 동기?
javascript module 공부하는 도중..
Cannot use import statement outside a module
라는 에러를 마주쳤습니다.
이 에러를 해결하기 위해서 .js파일을 .mjs파일로 변경하라는 해결책이 있었는데, 실제로 이를 적용하니 해결되었습니다.
해결되고나니 .mjs파일 와 .js파일의 차이점이 궁금해서 공부했습니다.

.mjs Vs .js
원래 Node.js의 모듈 시스템은 commonjs를 사용했습니다(require과 module.exports를 사용하는..)
그러다가 ECMAscript 모듈 시스템이 표준이 되었고, Node.js는 이를 지원하게 되었습니다.
Node.js 는 .cjs 파일로 commonjs 모듈 시스템을 지원했고,
.mjs파일로 ECMAsript 모듈 시스템을 지원했습니다.
그러고 js파일은 둘 다 모두를 지원하게 되었습니다.
(default는 commonjs)
(package.json에 "type" :"module"쓰면 ecma 모듈 지원)
.JS
const b = require("./main2.js");
console.log(b.a);
받아오는 js
function hello() {
return "hello";
}
const a = "a";
module.exports = {
hello: hello,
a: a,
};
보내주는 js
.mjs OR package.json에 타입 추가
import { hello, a } from "./main2.mjs";
console.log(`${hello()} ${a}`);
받아오는 js
function hello() {
return "hellozz";
}
const a = "a";
export { hello, a };
보내주는 js
반응형