본문 바로가기
프로그래밍

자바스크립트 : Modules (코드카데미)

by Youngbin Kwon 2020. 8. 17.

1. Require 함수를 통해 자바스크립트 모듈 import

require 함수를 통해 다른 파일에 있는 자바스크립트 모듈을 불러와 사용할 수 있다.

var moduleA = require( "./module-a.js" );

// The .js extension is optional
var moduleA = require( "./module-a" );
// Both ways will produce the same result.

// Now the functionality of moduleA can be used
console.log(moduleA.someFunctionality)

 

2. Export default

ES6에 추가된 내용으로, 함수 앞에 export default를 사용하여 해당 함수를 export할 수 있고, 해당 함수를 불러오고자 하는 파일에서는 import {함수명} from '불러올 파일 위치'를 선언하여 require없이 함수를 import할 수 있다.

// module "moduleA.js"
export default function cube(x) {
  return x * x * x;
}

// In main.js
import cube from './moduleA.js';
// Now the `cube` function can be used straightforwardly.
console.log(cube(3)); // 27

 

3. module.exports

자바스크립트 파일 내의 object를 export가능하게 하기 위해, module.exports 를 사용한다.

let Course = {};
Course.name = "Javascript Node.js"
module.exports = Course;

 

4. import 키워드 사용

import * from 'module_name'; 을 통해 해당 JS파일에서 모든 요소들을 import할 수 있다.

한 개의 함수를 import하기 위해서는 import {funcA} from 'module_name'; 과 같은 방법으로 import할 수 있다.

* 여러 개의 함수 import : import {funcA, funcB} as name from 'module_name';

// add.js
export const add = (x, y) => {
    return x + y
}


// main.js
import { add } from './add';
console.log(add(2, 3)); // 5

 

 

'프로그래밍' 카테고리의 다른 글

CSS : Box-sizing  (0) 2020.08.18
CSS : position  (0) 2020.08.18
자바스크립트 : class vs object (드림코딩)  (0) 2020.08.16
자바스크립트 : DOM  (0) 2020.08.15
자바스크립트 : Interactive Websites (코드카데미)  (0) 2020.08.12

댓글