본문 바로가기
⚙️백엔드/Node.js

node.js - 모듈 파일 불러오기(exports)

by Janger 2022. 2. 8.
728x90
반응형

 

다음과 같이 모듈 파일을 만들고

 

export 할 변수, 함수, 클래스들은 위와 같이 exports.{이름} = {변수|함수|클래스}로 지정해준다. 

 

require 함수를 통해서 외부의 js 파일을 불러와서 myModule이라는 변수에 대입을 해준다. 

 

실행 결과를 확인하면 myModule 안에는 message라는 변수와 say 함수가 들어있는 것을 확인 가능

 

 

이제 각각의 변수와 함수를 사용하기 위해서는 

myModule.message

myModule.say()

요런식으로 점 뒤에 키워드를 적는다. 

 

실행 결과

 

 

 

 

요약:

 

[수출하기]

var a = 123;

exports.a = a;

 

[수입하기]

const myModule = require('module.js');
const a = myModule.a;

 

 

참고: 

https://stackoverflow.com/questions/3922994/share-variables-between-files-in-node-js

 

Share variables between files in Node.js?

Here are 2 files: // main.js require('./modules'); console.log(name); // prints "foobar" // module.js name = "foobar"; When I don't have "var" it works. But when I have: // module.js var name = "

stackoverflow.com

 

728x90
반응형