webpack 기본 사용법
2021.11.12
1. 설치
-
npm package
npm init
-
webpack & webpack-cli install
npm install --save-dev webpack webpack-cli
2. 기본 설정
- 설정 파일 생성 webpack.config.js
webpack.config.js
const path = require("path");
module.exports = {
entry : "./src/index.js",
output : {
filename : "main.js",
path: path.resolve(__dirname, "dist")
}
}
- entry : 시작파일 이곳에서 시작해서 사용하는 모듈들을 파악
- output: 만들어지는 파일을 내보내는 옵션
- filename : 내보내질 파일명
- path : 파일 등 경로 작업
path: path.resolve(__dirname, "dist")
→ 현재 경로 하위에 dist 폴더를 의미
2.1. 테스트 하기
src/test.js
src/index.js
- package.json
"script" :{ "build" : "webpack" }
다음과 같이 추가 해주면 npm run build
을 실행 해주면 dist
폴더에 main.js
가 생긴 것을 볼 수 있다.
3. HTML 설정
여기 위에 까지 설정을 했다면 dist에 js파일만 있기 때문에 main.js를 다시 index.html 파일에 연결해 주어야한다.
배포를 할때 dist파일만 쉽게 하기 위해서 html설정을 해준다.
- 설치
npm install --save-dev html-webpack-plugin
→ 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. 웹팩 서버
웹팩은 수정할 때마다 계속 다시 빌드하고 서버를 실행 해주어야 한다.
이 것을 자동화 할 수 있다.
- 설치
npm --save-dev webpack-dev-server
- webpack.config.js 설정
webpack.config.jspackage.json
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 :{ static:{ directory: path.resolve(__dirname, "dist") }, port: 8080, } };
package.json위와 같이 명령어 설정을 해주면"script" :{ "start" : "webpack serve --open --mode=development", "build" : "webpack --mode=production" }
npm start
로 명령어를 치게 되면 8080가 열리게 된다. 참고로 서버는 개발자모드에서만 되기 떄문에 뒤에--mode=developmen
가있다.--mode=production
옵션은 배포용이다.
5. CSS 설정
npm install --save-dev style-loader css-loader
- css-loader :
css
파일을 읽어줌 - style-loader : 읽은
css
파일을 style 태그로 만들어서 헤드 내부에 넣어줌
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,
}
};
- test : 확장자가
.css
일떄 use 옵션 한다. - use: 뒤에서 부터 적용된다
그래서 css를 가져오고 style로 만들어 주어야 되서
use: ["style-loader","css-loader"]
으로 씀
5.2. CSS 별도 파일로 가져와서 사용하기
위에 까지 하고 실핼 할경우 head태그 영역에 style로 바로 들어간다
css파일을 따로 만들어서 import시켜주는 방법이다.
-
플러그인 설치
npm install --save-dev mini-css-extract-plugin
-
webpack.config.js 설정
webpack.config.jsconst path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-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"], use: [MiniCssExtractPlugin.loader,"css-loader"] } ] }, plugins: [ new HtmlWebpackPlugin({ template:"./index.html" }), new MiniCssExtractPlugin({ filename: "common.css", }), ], devServer :{ static:{ directory: path.resolve(__dirname, "dist") }, port: 8080, } };
6. 이미지 설정
npm install --save-dev file-loader
- webpack.config.js 설정
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 : { filename : "main.js" path: path.resolve(__dirname, "dist") }, module:{ rules: [ { test : /\.css$/, //use: ["style-loader","css-loader"], use: [MiniCssExtractPlugin.loader,"css-loader"] }, { test : /\.jpg$/, use: ["file-loader"] } ] }, plugins: [ new HtmlWebpackPlugin({ template:"./index.html" }), new MiniCssExtractPlugin({ filename: "common.css", }), ], devServer :{ static:{ directory: path.resolve(__dirname, "dist") }, port: 8080, } };
다음과 같이 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
- webpack.config.js 설정
webpack.config.js
const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin") const { CleanWebpackPlugin } = require("clean-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"], use: [MiniCssExtractPlugin.loader,"css-loader"] }, { test : /\.jpg$/, use: ["file-loader"] } ] }, plugins: [ new HtmlWebpackPlugin({ template:"./index.html" }), new MiniCssExtractPlugin({ filename: "common.css", }), new CleanWebpackPlugin(), ], devServer :{ static:{ directory: path.resolve(__dirname, "dist") }, port: 8080, } };
참고로 이 플러그인은 로 해주어야한다.
이렇게 설정하고 빌드하면 자동으로 지워줌