T_era
[JavaScript] 서로 다른 스크립트 참조하기 본문
현대 JavaScript 환경에서는 주로 ES Modules 방식을 사용하며, 이전 방식으로는 CommonJS가 있다
오늘은 ES Module에 대해 알아보자
1. ES Modules (ECMAScript Modules)
내보내기 (Export): 참조될 파일에서 export 키워드를 사용하여 변수, 함수, 클래스 등을 내보냅니다.
// moduleA.js
export const myVariable = 10;
export function myFunction() {
console.log('Hello from myFunction');
}
export class MyClass {
constructor() {
console.log('MyClass instance created');
}
}
가져오기 (Import): 다른 파일에서 import 키워드를 사용하여 내보내진 항목을 가져옵니다.
// moduleC.js
import { myVariable, myFunction, MyClass } from './moduleA.js';
console.log(myVariable); // 10
myFunction(); // Hello from myFunction
const instance = new MyClass(); // MyClass instance created
위와 같이 moduleA.js에서 함수를 정의할 때 export를 추가해 참조할 수 있는 준비를 하고
moduleC.js에서 사용한 것 처럼 import {이름} from 'js경로';를 사용해 참조하여 사용할 수 있다
import할 때 export에 작성한 함수명 변수명 클래스명 등은 전부 동일하게 작성해야한다
'Programing > Html' 카테고리의 다른 글
| [JavaScript] submit과 click (0) | 2025.04.09 |
|---|---|
| [Firebase] CORS 정책 - 2 (0) | 2025.04.09 |
| [Firebase] CROS정책 - 1 (0) | 2025.04.08 |
| Firebase를 프로젝트에 적용하기 (0) | 2025.03.19 |
| Firebase 시작하기 (0) | 2025.03.19 |