[JavaScript] Webpack - common js 표준으로 내보내는 방법

손종일·2020년 10월 18일
0

Webpack

목록 보기
2/5
post-thumbnail

Webpack

common js로 내보내는 방법

아래의 코드는 사각형 넓이를 구하는 공식과 결과값을 표기한 파일입니다.
해당 파일을 나누어 관리해보도록 하겠습니다.

const width = 4;				<index.js>
const getSquareArea = height =>  height * width;
const result = getSquareArea(3);
console.log(result) // 12

첫번째로는, 아래의 코드는 가로와, 공식을 mathUtils라는 모듈로 분리하고 해당 모듈에서 전체를 불러와 사용하였습니다.

const width = 4;					<mathUtils.js>
const getSquareArea = height =>  height * width;
// 모듈 전체를 내보내어 줍니다.
module.exports = {
    width,
    getSquareArea
  // key 와 value값이 일치하다면 하나만 써주어도 됩니다.
}
// mathUtils에서 내보낸 전체를 받아줍니다.
const {getSquareArea} = require('./mathUtils')		<index.js>
const result = getSquareArea(3);
console.log(result)			// 12

두번째로는, 아래의 코드는 가로와, 공식을 mathUtils라는 모듈로 분리하고 해당 모듈에서 개별적으로 내보낸 것을 불러와 사용하였습니다.

const width = 4;					<mathUtils.js>
const getSquareArea = height =>  height * width;
// 모듈 개별적으로 내보내어 줍니다.
exports.width = width;
exports.getSquareArea = getSquareArea;
// mathUtils에서 내보낸 전체를 받아줍니다.
const {getSquareArea} = require('./mathUtils')		<index.js>
const result = getSquareArea(3);
console.log(result)			// 12
profile
Allday

0개의 댓글