본문 바로가기
웹 프로그래밍 기초/자바기반의 웹&앱 응용SW 개발자

자바기반의 웹&앱 응용 SW개발자 양성과정 77일차 -114

by oncerun 2020. 7. 3.
반응형

모듈은 외부 js파일의 함수를 import 해서 사용할 수 있도록 도와준다.

이전 js파일은 전부 html에 <script>태그에 넣어서 사용했다.

당연했던 기능이 스크립트에서는 지원되지 않았습니다.

이러한 기능을 제공했는데 그것이 모듈화입니다.

 

함수에서만 국한되는 것이 아니라 클래스 또한 가능합니다.

 

 

module.js 에서 외부로 노출시킬 api를 export로 등록해준 뒤.

export const test1 = () => {

    console.log("module1");

}

export const test2 = () => {

    console.log("module2");

}

export const test3 = () => {

    console.log("module3");
}

export default test2;

사용하는 js에서 import를 해줍니다.

import asd, { test1 } from './module1.js';


asd();
test1();

default로 설정된 api는 별칭으로 받을 수 있습니다.

 

class를 export와 import 하는 방법은 간단합니다.

모듈 코드가 객체지향적으로 작성된 경우 유용합니다.

하나의 JS파일이 단일 클래스에 모든 기능이 존재하는 경우 import 해서 정의된 오브젝트의 기능을 사용할 수 있습니다.

export const test1 = () => {

    console.log("module1");

}

export const test2 = () => {

    console.log("module2");

}

export const test3 = () => {

    console.log("module3");
}

export class Exam {


    constructor(kor, math, eng) {
        this.kor = kor;
        this.math = math;
        this.eng = eng;
    }

    total() {

        return this.kor + this.math + this.eng;
    }
}


export default test2;

 

import asd, { test1, test3, Exam } from './module1.js';


asd();
test1();

let exam = new Exam(1, 2, 3);
console.log(exam);
console.log(exam.total());
반응형

댓글