Webpack 세팅하기 (HTML, CSS, JS)

๑'ٮ'๑·2022년 8월 8일
0

webpack 설치

npm init -y
npm i webpack webpack-cli -D
  • -D : 개발 단계에서만 사용하도록 설치
  • package.jsondevDependencies에 들어가게 된다.

webpack.config.js

entry (시작점)

  • 불러온 모듈의 시작점이 되는 파일
  • 이 지점을 바탕으로 모듈간 의존성 그래프를 그린다.

output (출력)

  • 번들링 된 결과파일 경로를 지정
// webpack.config.js

const path = require("path");
// 경로를 조합해주는 node.js API

module.exports = {
	entry: "./src/index.js",
  	output: {
      	filename: "bundle.js",
      	path: path.resolve(__dirname, "dist"),
      	// npm build (webpack) 실행 시 dist 폴더에 bundle.js 생성됨
    }
  	
}

loader

  • CSS, 이미지 파일을 모듈 형태로 자바스크립트 안에 불러올 수 있다.
npm i -D style-loader css-loader file-loader
// webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
        // use 배열 안의 Loader들은 뒤에서부터 적용된다.
        // css-loader로 읽고 style-loader로 html에 style 태그 추가
      },
      {
        test: /\.(jpg|png|gif)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[name].[ext]",
            }
          }
        ]
      }
    ]
  }
}

plugins

  • html-webpack-plugin : 번들 파일이 들어가있는 index.html을 자동으로 생성해주는 플러그인
  • clean-webpack-plugin : build 폴더에 불필요한 파일 삭제
  • mini-css-extract-plugin : css 파일을 별도로 만들어서 build 하고싶을 때 사용
npm i -D html-webpack-plugin clean-webpack-plugin
// webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
	plugins: [
      new HTMLWebpackPlugin({
        template: "index.html"
        // template -> 기존에 만들었던 html파일을 바탕으로 생성
      }),
      new CleanWebpackPlugin(),
    ],
}

+ devServer

개발서버

npm i webpack-dev-server -D
// webpack.config.json
module.exports = {
	devServer: {
    	static: {
        	directory: path.resolve(__dirname, "dist"),
        },
      	port: 8080,
    },
}
// package.json
"scripts": {
	"start": "webpack serve --open --mode=development",
}

🔗 Reference

profile
프론트엔드

0개의 댓글