program/javascript

[javascript] 모듈 .mjs Vs .js

momoa210 2024. 2. 12. 11:43

.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

 

'program > javascript' 카테고리의 다른 글

[javascript]null vs undefined  (0) 2024.02.04
[javascript] truthy falsy  (0) 2024.02.04
[javascript] 형변환  (0) 2024.02.04
[javascript] 자료형  (0) 2024.02.04
[javascript] null vs undefined  (0) 2024.02.03