728x90

자바스크립트 모듈이 뭐야?

  • 모듈(Module) = 코드를 여러 파일로 나눠서 관리하기 위한 기능
  • 큰 프로젝트일수록 파일 분리가 필수
  • ES6 이전 → 자바스크립트엔 공식 모듈 시스템이 없었음
  • 지금은 대표적으로 CommonJSES Module 두 가지가 많이 쓰임

✅ CommonJS

특징

  • Node. js에서 사용하기 위해 만들어짐
  • 동기적으로 동작 (require 시점에 파일 읽음)
  • 파일마다 scope가 분리됨
  • .js 확장자 생략 가능

CommonJS 코드 예제

math.js

const perfectSore = 100;

function sum(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = {
  perfectSore,
  sum,
  subtract,
};

index.js

const math = require('./math.js');

console.log('perfectSore', math.perfectSore);
console.log('sum', math.sum(10, 20));
console.log('subtract', math.subtract(10, 20));

실행 방법

  • Node.js 환경에서 바로 실행 가능
  • package.json 없어도 OK
  • 예:
node commonjs/index.js

✅ ES Module (ESM)

특징

  • ES6(ECMAScript 2015)에서 공식 표준으로 도입
  • 비동기적으로 동작 가능
  • 파일 간 의존 관계가 명확해짐
  • 브라우저Node.js 둘 다 사용 가능 (Node.js에서는 설정 필요)
  • Node.js에서는 package.json에 설정해야 함:
{
  "type": "module"
}

ES Module 코드 예제

math.js

export const perfectSore = 100;

export function sum(a, b) {
  return a + b;
}

export function avege(a, b) {
  return (a + b) / 2;
}

export default {
  subtract(a, b) {
    return a - b;
  }
};

index.js

import { perfectSore, sum, avege } from './math.js';
import math from './math.js';

console.log('perfectSore', perfectSore);
console.log('sum', sum(10, 20));
console.log('avg', avege(10, 20));
console.log('subtract', math.subtract(10, 20));

import 문법 종류

  • 개별 import
import { sum } from './math.js';
  • default import
import math from './math.js';
  • 모든 export 한 번에 가져오기
import * as math from './math.js';
console.log(math.sum(10, 20));

실행 방법

Node.js에서 ES Module 사용하려면:

  • package.json 추가
{
  "type": "module"
}
  • 실행:
node module/index.js

✅ CommonJS vs ES Module 비교

구분 CommonJS ES Module
도입 시기 예전부터 (Node.js 초창기) ES6 (ECMAScript 2015)
문법 require / module.exports import / export
동기/비동기 동기 비동기 가능
브라우저 사용 X (변환 필요) O (모던 브라우저 지원)
Node.js 기본 지원 package.json 설정 필요
 

✅ 비유로 이해하기

  • CommonJS → 즉석 전화: “전화해 보고 바로 대답 듣기” (동기적)
  • ES Module → 메일: “보내놓고, 답 오면 처리” (비동기 가능)

✅ 정리

  • 작은 파일로 나누고 import/export 하는 습관은 유지보수 필수
  • Node.js에서는 CommonJS도 여전히 많이 쓰지만, 최신 프로젝트는 ES Module로 점점 이동
  • 브라우저에서 모듈 쓸 땐 <script type="module"> 꼭 확인!
728x90
728x90

1. 이벤트 전파: 버블링 vs 캡처링


✅ DOM 중첩 구조 예시

네가 올린 이미지처럼 DOM은 아래처럼 중첩된 박스처럼 되어 있어:

body
└─ main
    └─ div
        └─ p
            └─ span

이벤트는 이렇게 안쪽 ↔ 바깥쪽으로 흘러간다.


캡처링 (Capturing Phase)

  • 이벤트가 가장 바깥쪽 → 가장 안쪽으로 전파
  • 예: body → main → div → p → span
  • 흔히 캡처 단계라고 부름

타깃 단계 (Target Phase)

  • 이벤트가 실제로 발생한 요소에서 실행
  • 예: span에서 클릭 발생

버블링 (Bubbling Phase)

  • 이벤트가 안쪽 → 바깥쪽으로 전파
  • 예: span → p → div → main → body
  • 디폴트 동작은 대부분 버블링

✅ event.eventPhase 값

event.eventPhase로 현재 단계 알 수 있음

eventPhase 값 의미
1 Capturing Phase
2 Target Phase
3 Bubbling Phase
 

✅ 버블링/캡처링 코드 예시

HTML

 
<div id="outer">
  <div id="inner">클릭해보세요!</div>
</div>
js
 
document.getElementById("outer").addEventListener(
  "click",
  (e) => {
    console.log("outer div 캡처링 단계", e.eventPhase);
  },
  true // 캡처링
);

document.getElementById("inner").addEventListener(
  "click",
  (e) => {
    console.log("inner div 버블링 단계", e.eventPhase);
  },
  false // 버블링
);

2. JS 모듈 import/export


✅ ES6 모듈 기본 문법

1) export

파일 math.js

export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

2) import

파일 main.js

import { add, multiply } from "./math.js";

console.log(add(2, 3)); // 5
console.log(multiply(2, 3)); // 6

default export

math.js

export default function subtract(a, b) {
  return a - b;
}

main.js

import subtract from "./math.js";
console.log(subtract(5, 2)); // 3

✅ 모듈 사용 시 주의

  • import/export는 브라우저에서 type="module" 필요
  • html
     
<script type="module" src="main.js"></script>

3. Array API


✅ map

  • 배열의 각 요소를 변환 → 새로운 배열 반환
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6]

✅ some

  • 배열 중 하나라도 조건 만족하면 true
const nums = [1, 2, 3];
console.log(nums.some(n => n > 2)); // true

✅ reduce

  • 배열 요소를 하나의 값으로 누적
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10

✅ filter

  • 조건에 맞는 요소만 추출 → 새로운 배열
const nums = [1, 2, 3, 4];
const even = nums.filter(n => n % 2 === 0);
console.log(even); // [2, 4]

✅ 마무리

오늘은 프런트엔드 개발자가 꼭 알아야 할

  • 이벤트 전파 (버블링/캡처링)
  • ES6 모듈 시스템
  • Array API (map, some, reduce, filter)
    를 정리했어.

작은 차이를 이해하면 코드가 더 깔끔하고 효율적해질 수 있으니 꼭 익혀두자!

728x90

+ Recent posts