웹팩을 사용하면 아래와 같이 복잡한 상태를 하나의 파일로 번들링 할 수 있다.
- 번들링 될 파일들 경로 불러오기
- 번들된 아웃풋 파일 경로 지정
- 번들된 파일을 html에서 불러 들여오기
- Dev server를 활용하여 자동으로 번들, 리프레쉬, 브라우저 실행하기
설치할 파일
- webpack
- webpack-cli@4.9.0
- gitignore
- webpack-dev-server@4.0.0
폴더 및 파일 설명
- bin : bundle.js 번들된 파일
- public : html -> 번들된 js파일을 불러오기
- src : index.js 번들할 파일
- webpack.config.js : 경로 설정
- package.js : 실행 명령어 설정
example
./src
index.js
types.d.ts
component.jsx
config.json
language/index.ts
./bin
bundle.js
버전
Webpack을 사용하기 전에 자신의 프로젝트에 어떤 웹팩이 맞는지 생각해봐야한다.
웹팩은 다양한 버전을 갖고 있다.
- Webpack 2: 구식, 사용가능
- Webpack 3: 대부분 사용 완벽하지 않음
- Webpack 4: 사용하기 어려움
- Webpack 5: 최신식, 어려움
버전 선택
- 2 어쩔 수 없을때
- 3 실용적
- 4 성능과 실용성
- 5 성능
3,4,5 는 어찌됐던 좋은 선택이다.
작동원리
- 파일들이 메모리로 올라감
- 브라우저가 이해할 수 있는 코드들로 변환됨
- 코드가 아닌 파일들이 코드들에 임베드 됨
설치
npm install --save-dev webpack webpack-cli@4.9.0
package.json 수정
"scripts": { "test": "echo \"Error: no test specified\" && exit 1" }"scripts": { "test": "webpack" }
gitignore node modules
npm install -g gitignore gitignore node
Webpack.config.js 세팅
- Input files
- Output files
- 라이브러리 설정
- 옵션 설정
웹팩은 여러 파일들을 담아 bin이나 dist폴더에 한개의 파일로 번들링 해 준다.
Process
- webpack.config.json 파일 생성하기
- 수정
mode, target, entry, output
- hello world 만들기
webpack.config.json 파일 생성하기
const {resolve} = require('path');
module.exports = {
target: "web", // 노드가 아니라 웹브라우저가 대상.
mode: "development", // 배포용 모드.
entry: "./src/index.js", // 입력 파일.
output:{
path: resolve(__dirname, "bin"), // 출력 파일의 위치. 절대 경로. 오브젝트 타입.
filename: "bundle.js" // 출력 파일.
}
}
npm test
노드를 실행하면 bin 폴더에 bundle.js가 생성된다.
- 번들링을 자동으로 한다.
- 브라우저를 자동으로 연다.
- 코드가 변경되면 브라우저를 자동으로 리프레쉬 한다.
webpack.config.js
,
devServer: {
static: resolve(__dirname, "public"),
port: 7777,
}
}
npm install --save-dev webpack-dev-server@4.0.0
package.json
"scripts": {
"build": "webpack",
"serve": "webpack serve"
},
실행
webpack serve