개발 끝내고 배포 시,
bundle
사이즈는 항상 신경을 써야 됨.
lodash
를import
하는 방식에 따라서 최종bundle js
의 사이즈가 달라짐.
// lodash-es 활용 (아래 中 택 1)
import each from "lodash-es/each";
import { each } from "lodash-es";
실행 사항
Webpack | 개념 / 필수 개발 환경 세팅 1 의 과정 (설치 / 설정)
中 1, 2, 3 참고, 6 -1
(지식)
src/index.js
console.log(3);
webpack.config.js
webpack
이용해서 dist
폴더에 main.js
파일 제작
// webpack.config.js 코드
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
},
};
빌드
npm run build
결과 확인
15 bytes
라고 나옴.
작업본과 최종 결과본 차이: 없음
npm i lodash
_
- 방법:
import _ from "lodash"
- 결론:
✔ 번들 사이즈 크기 → 불필요하게 커짐.
✔ (사용하지 않는 함수들까지) 모두 불러옴.
src/index.js
import _ from "lodash" // 👈 대부분이 사용하는 방법
const arr = [1, 2, 3, 4, 5];
_.each(arr, (num) => {
console.log(num, "hello");
});
빌드
npm run build
결과 확인
크기 커진 이유: lodash
추가
dist/main.js
결과물: 엄청 길어짐.
작성한 코드 위치: 맨 아래
대부분 lodash
의 모든 기능을 사용하진 않음.
- 방법:
import { 메소드명 } from "lodash"
- 결론:
✔ 첫 번째import
방법과 동일한 크기 (== 결과본 차이: 無)
✔ 모든 모듈들 포함
src/index.js
import { each } from "lodash"; // 👈
/*
다른 함수들 추가:
{ each, 다른 함수명1, 다른 함수명2, ... } */
const arr = [1, 2, 3, 4, 5];
each(arr, (num) => {
console.log(num, "hello");
});
빌드(npm run build
)
결과 확인
- 방법:
import 메소드명 from "lodash/메소드명"
- 결론:
✔ 크기 (10배 이상) 감소 (필요한 모듈들만 가져와서)
src/index.js
import each from "lodash/each"; // 👈
const arr = [1, 2, 3, 4, 5];
each(arr, (num) => {
console.log(num, "hello");
});
빌드(npm run build
)
결과 확인
크기 : 5.58 KiB
dist/main.js
결과물: 확연히 줄어듦.
- 방법: 설치 후,
import 메소드명 from "lodash-es/메소드명"
- 결론:
✔ 크기 더 감소 (가장 작음)
설치
npm i lodash-es
src/index.js
// // 2가지 모두 동일하게 Tree shaking 됨
import each from "lodash-es/each"; // 👈 1.
import { each } from "lodash-es"; // 👈 2. named import 방식
const arr = [1, 2, 3, 4, 5];
each(arr, (num) => {
console.log(num, "hello");
});
빌드 (npm run build
)
결과 확인
크기 감소 : 3.73 KiB
Tree shaking
이란?
필요 없는 코드들을 턴다 (나무를 흔든다)
webpack4
버전 이상 (ES Module
로 의존성을 관리하는 모듈만) 지원
lodash
: CommonJS
사용 → Tree shaking
불가
CommonJS
문법 이란? webpack.config.js
의 module.exports
처럼 해주는 것 lodash-es
: ES Module
(import export default
사용) 사용 → Tree shaking
의 대상
모듈의 크기를 자동으로 계산해주는 VS Code의 익스텐션
참고