모듈이란?
독립적인 특성을 가진 기능 단위의 부품
프로그램의 기능을 독립적인 부품으로 분리한 것
동시에 여러 다른 모듈과 함께 조합하여 재사용가능
Common.js
자바스크립트에서 제공하는 하나의 모델 시스템
서버와 동기
cosnt module = reuire('module');
module.exports = module;
person.js 파일
function Person(name, age, lacation){
this.name = name;
this.age =age;
this.location = location;
this.getName = function(){
retrun this.name + '입니다';
}
}
module.exports = Person;
test.js
- require를 톻해 메소드를 불러온다.
const Person = require('경로/pserson.js');
const me = new Person('jang', 10, 'Korea');
const you = new Person('kim',20,'china');
console.log(me.getName());
console.log(you.getName());
AMD
모듈을 선언하면서 의존하고 있는 모듈을 함께 명시한다.
비동기적을로 의존 모듈을 불러온다.
브라우저와 비동기
define(['module'],fuction(module){
return function() {
}
});
UMD
AMD와 CommonJS 두 방식 모두 지원
클라이언트, 서버 어디에서나 작동된다.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define([], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS
module.exports = factory();
} else {
// Browser globals
root.myModule = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
// 모듈 코드
function myFunction() {
console.log('Hello from UMD module!');
}
return {
myFunction: myFunction
};
}));
es-module
모듈을 내보내기, 가져오기 가능하다
expoer.js
export const a = 'a';
export function hello(){
return 'hello';
}
import.js
import {a, hello} from '경로/export.js';
cosole.log(a);
- 내보내기가 하나 일 때
expoer.js
export default function hello(){
return 'hello';
}
import.js
import h from '경로/export.js'; // 변수명 마음대로 변경 가능
cosole.log(h);
'자바스크립트' 카테고리의 다른 글
[JavaScript] Async & Await (0) | 2025.02.19 |
---|---|
[JavaScript] 탭기능 만들기 (0) | 2025.02.19 |
[JavaScript] Promise 정복하기 (1) | 2025.02.14 |
[JavaScript] 프로그래머스 제곱수 판별하기 (0) | 2025.01.09 |
[JavaScript] 프로그래머스 문자열안에 문자열 (0) | 2025.01.08 |