Server & Node - Common JS

Verba volant, scripta manent·2021년 2월 10일
0

Common JS란?

모든 모듈은 자신만의 독립적인 실행 영역이 있어야 한다.

// foo.js
exports.foo = () => { ... };
// bar.js
exports.bar= () => { ... };

모듈 정의는 전역객체인 exports 객체를 이용한다.

// foobar.js
exports.foobar= () => { ... };

모듈 사용은 require 함수를 이용한다.

<script>
var $ = require('jquery');
var foo = require('./js/foo');
var bar = require('./js/bar');
var foobar = require('./js/foobar');
</script>

module.exports vs exports

// --  hello.js
module.exports.anything = function() {
  console.log('I am anything.');
};
// -- hello-runner.js
const hello = require('./hello');
// let's see what's there in hello variable
console.log(hello); // {anything: Function}
hello.anything(); // I am anything.
// --  hello.js
exports.anything = function() {
  console.log('I am anything.');
};
// -- hello-runner.js
const hello = require('./hello');
// let's see what's there in hello variable
console.log(hello); // {anything: Function}
hello.anything(); // I am anything.

exports는 module.exports 사용을 도와주는 helper
exports는 module.exports를 참조할 뿐이다.

profile
말은 사라지지만 기록은 남는다

0개의 댓글

관련 채용 정보