Webpack + Vanilla JavaScript, HTML, CSS 개발 환경을 세팅해보자.
웹팩은 다수의 자바스크립트 파일(모듈)을 하나의 자바스크립트 파일로 묶어(번들링)주는 모듈 번들링이다.
요즘에는 페이지마다 html을 만들어서 뿌리는 형식이 아닌 하나의 html에 여러 자바스크립트를 연결해서 보여주는 SPA 형식으로 구현된 웹 페이지가 많다.
웹팩을 사용하면 여러 종속성으로 얽혀있는 자바스크립트 파일을 정리해서 하나로 빌드해주기 때문에 배포할 때도 엄청나게 \\ 유용하다.
project
├── index.html
└── src
└── index.js
npm init -y
npm install webpack-cli --save-dev
💡 최신 npm은
--save
가 기본으로 설정되어 있어서 따로 적어주지 않아도 된다.
touch webpack.config.js
(webpack.config.js)
// path 모듈 불러오기
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
// 최종 번들링된 자바스크립트
filename: 'main.js',
// dist를 배포용 폴더로 사용
path: path.resolve(__dirname, 'dist')
}
}
- entry: 배포 전 작업용 자바스크립트 시작점
- output: 최종 배포용 번들링 파일 설정
"scripts": {
"build": "webpack"
},
npm run build
dist 폴더가 생성되는 것을 확인할 수 있다. 내부에는 main.js 파일이 생성되어 있다.
모든 자바스크립트 파일이 합쳐져서 main.js로 bundle될 것이다.
npm install html-webpack-plugin
const path = require('path');
// html 플러그인을 불러오고
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
// 여기에 설정
plugins: [new HtmlWebpackPlugin({
template: "./index.html" // index.html을 기본 템플릿으로 반영할 수 있도록 설정
})]
}
npm run build
base-project
├── dist
│ ├── index.html
│ └── main.js
├── index.html
├── package-lock.json
├── package.json
├── src
│ └── index.js
└── webpack.config.js
webpack-dev-server를 설치하면 실시간으로 업데이트된 내용을 화면에서 확인할 수 있다.
npm install webpack-dev-server -D
💡
-D
=--save-dav
(webpack.config.js)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [new HtmlWebpackPlugin({
template: "./index.html"
})],
devServer: {
// 개발 서버가 dist 폴더를 제공할 수 있도록 설정
static: {
directory: path.resolve(__dirname, 'dist')
},
port: 8080
}
}
(package.json)
"scripts": {
"start": "webpack serve --open --mode=development",
"build": "webpack --mode=production"
},
npm start
: 개발 모드에서 사용하는 명령어이기 때문에--mode=development
로 모드를 설정해준다.npm run build
: 프로덕션 모드에서 사용하는 명령어이기 때문에--mode=production
로 모드를 설정해준다.
npm start
head에 스타일을 직접 작성하는 방식으로 스타일을 적용해보자.
npm install -D css-loader style-loader
- css-loader : css 파일을 읽어주는 역할
- style-loader : css를
<style>
태그로 만들어서<head>
내부에 삽입해준다.
...
module.exports = {
entry: './src/index.js',
output: {
...
},
plugins: [new HtmlWebpackPlugin({
...
})],
module: {
rules: [
{
test: /\.css$/,
// use 배열은 뒤에서부터 적용된다.
use: ["style-loader", "css-loader"]
}
]
},
devServer: {
...
}
}
project
├── dist
│ ├── index.html
│ └── main.js
├── index.html
├── package-lock.json
├── package.json
├── src
│ ├── index.js
│ ├── style.css
│ └── util.js
└── webpack.config.js
(src/index.js)
// css를 가져온다
import './style.css'
document.getElementById("root").innerHTML = '안녕하세요✌️';
(src/style.css)
body {
font-size: 30px;
color: blue;
}
(index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<!-- 스크립트를 삽입하지 않아도 웹팩에서 자동으로 스크립트를 삽입해준다. -->
<!-- 아래 코드는 필요없다-->
<!-- <script src="./dist/main.js"></script> -->
</body>
</html>
npm start
<head>
영역에 <script>
와 <style>
이 자동으로 들어와 있음을 확인할 수 있다.
외부 css 파일을 불러오는 방식으로 스타일을 적용해보자.
npm install -D mini-css-extract-plugin
(webpack.config.js)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 플러그인을 불러온다
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
output: {
...
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html"
}),
// 플러그인 추가
new MiniCssExtractPlugin({
filename: "common.css",
})
],
module: {
rules: [
{
test: /\.css$/,
// 다시 설정한다.
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
devServer: {
...
}
}
💡 internal 방식은 build 해도 CSS 파일이 따로 생성되지 않는다. 바로 head에 작성되기 때문이다.
반면, external 방식은 build 하면 별도의 CSS 파일이 생성된다.
이번에는 이미지를 빌드하기 위해 로더를 설치한다.
npm install -D file-loader
💡 Loader?
웹팩은 자바스크립트 파일뿐만 아니라 모든 웹 자원들도 모듈로 인식한다.
자바스크립트 파일에 이미지나 CSS 파일을 import해서 사용할 수 있게 해주는 게 바로 Loader다.
Loader는 빌드할 때 import한 자바스크립트 파일이 아닌 리소스들을 해석하고 변환해주는 역할을 한다.
(webpack.config.js)
...
module.exports = {
entry: './src/index.js',
output: {
...
},
plugins: [
...
],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
// file-loader 세팅
{
test: /\.(png|jpe?g|gif|svg|webp)$/i,
use: ['file-loader'],
}
]
},
devServer: {
...
}
}
build에 포함됐던 파일이 필요 없어졌을 때 삭제하고 다시 build하면 그대로 남아있는 것을 확인할 수 있다.
사용하지 않는 build 파일을 자동으로 삭제해주는 플러그인을 설치해보자.
npm install -D clean-webpack-plugin
(webpack.config.js)
...
module.exports = {
entry: './src/index.js',
output: {
...
},
plugins: [
...
],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
// file-loader 세팅
{
test: /\.(png|jpe?g|gif|svg|webp)$/i,
use: ['file-loader'],
}
]
},
devServer: {
...
}
}
많은 도움 얻고 갑니다! 감사합니다!