Webpack - 웹팩은 뭘 해주는 녀석일까 (간단한 실습을 통해 이해해보기)
개요)
실습1
: HTML에서 script를 load 했을 때 불편한 점을 이해하기
실습2
: 실습1에서 느꼈던 불편한 점을 해결해주는 웹팩
[실습1]
1. HTML, js 파일 두 개를 생성함
- 연습할디렉토리
- index.html
- src
- index.js
- hello-world.js
2. html, javascript 작성하기
[index.html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./src/index.js"></script>
<script src="./src/hello-world.js"></script>
</body>
</html>
[index.js]
// index.js
helloWorld();
[hello-world.js]
//hello-world.js
function helloWorld() {
console.log("Hello World");
}
index.html을 보면
helloWorld 함수를 실행하는 hello-world.js 파일을 먼저 불러오고 있다.
실행해보면
함수를 선언을 먼저 하지 않아서
에러가 발생한다.
[실습2] 웹팩 사용해 해결해보기
1. webpack 패키지 설치
npm install webpack webpack-cli --save-dev
webpack-cli는 명령어로 웹팩 다루게 해주는 패키지
2. index.js, hello-world.js 소스 수정
// hello-world.js
function helloWorld() {
console.log("Hello World");
}
export default helloWorld;
//index.js
import helloWorld from './hello-world.js';
helloWorld();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./src/index.js"></script>
<script src="./src/hello-world.js"></script>
</body>
</html>
똑같이
index.js부터 실행한다.
webpack 이전에는
index.js에서는 선언하지 않은 함수를 실행하여
오류가 발생했다.
웹팩으로 빌드 후
index.html를 로드하면 어떻게 될까?
3. 웹팩으로 빌드하기
npx webpack
빌드가 되면
dist 디렉토리에 main.js 파일이 생성되어 있는 걸 확인할 수 있다.
main.js 는
index.html이 load하는 script를 합쳐서 빌드한 파일이다.
main.js = index.js + hello-world.js
브라우저에서 main.js를 load하여
html파일을 열어보자
4. main.js를 load한 index.html 파일 만들어서 열어보기
dist 디렉토리 아래에
index.html 파일을 생성한다.(기존에 만들었던 index.html 아님)
[dist/index.html]
<!-- dist/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
위 이미지에 로드된 스크립트 파일은
main.js = index.js + hello-world.js
두개가 합친거다.
브라우저에서 열어보자
잘 나오는 것을 확인할 수 있다.
* webpack 빌드할 때 자세히 보고 싶으면 다음 옵션 추가
npx webpack --stats detailed