webpack 기본 사용법

1. 설치

2. 기본 설정

webpack.config.js
const path = require("path");

module.exports = {
	entry : "./src/index.js",
	output : {
		filename : "main.js",
		path: path.resolve(__dirname, "dist")
	}

}

2.1. 테스트 하기

src/test.js

src/index.js

다음과 같이 추가 해주면 npm run build을 실행 해주면 dist폴더에 main.js가 생긴 것을 볼 수 있다.

3. HTML 설정

여기 위에 까지 설정을 했다면 dist에 js파일만 있기 때문에 main.js를 다시 index.html 파일에 연결해 주어야한다.

배포를 할때 dist파일만 쉽게 하기 위해서 html설정을 해준다.

→ HTML설정은 플러그인이게 때문에 다음과 같이 적어준다.

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"
			}),
		],
};

플러그인할때 template설정은 기존에 있던 ./index.html파일을 바탕으로 만들어 주게 된다.

만약 이 옵션을 안주면 코드의 title이라던가 몇몇 부분이 다르게 나온다.

4. 웹팩 서버

웹팩은 수정할 때마다 계속 다시 빌드하고 서버를 실행 해주어야 한다.

이 것을 자동화 할 수 있다.

5. CSS 설정

npm install --save-dev style-loader css-loader

5.1. CSS config 설정

html은 플러그인이고 css는 모듈로 작성을 해야함

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")
		},
		module:{
			rules: [
				{
					test : /\.css$/,
					use: ["style-loader","css-loader"]
				}
			]
		},
		plugins: [
			new HtmlWebpackPlugin({
				template:"./index.html"
			}),
		],
	devServer :{
		static:{
			directory: path.resolve(__dirname, "dist")
		},
		port: 8080,
	}
};

5.2. CSS 별도 파일로 가져와서 사용하기

위에 까지 하고 실핼 할경우 head태그 영역에 style로 바로 들어간다

css파일을 따로 만들어서 import시켜주는 방법이다.

6. 이미지 설정

npm install --save-dev file-loader

다음과 같이 index.html 파일에 img를 넣을 수 있다.

index.html
import logo from "./images/logo.png";

const img = `<img src="${logo}" />`;

document.getElementById("root").innerHTML = img;

7. 사용하지 않는 파일 지우기

dist에 사용하지 않는 파일이 남아 있는 것을 지워준다.

npm install --save-dev clean-webpack-plugin

이렇게 설정하고 빌드하면 자동으로 지워줌