웹팩 실습

이전 포스트에서는 웹팩이 어떻게 등장했는지, 모듈 개념, 그리고 웹팩의 기본 개념에 대해 알아보았다. 이번 포스트에서는 웹팩을 실제 설치해보고 자주 사용하는 플러그인들에 대해 알아보고 추가해보자.

1. webpack.config.js

1.1 mode, entry, output 옵션
const path = require("path")

module.exports = {
  mode: "development",
  entry: "./src/js/index.js",
  output: {
    filename: "bundle.js",
        path: path.resolve(__dirname, "./dist"),
        clean: true
  },
}

package.json:

{
  "scripts": {
    "build": "webpack",
  }
}

2. plugins 옵션

2.1 BannerPlugin
const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.BannerPlugin({
      banner: () => `빌드 날짜: ${new Date().toLocaleString()}`,
    })
  ]
2.2 DefinePlugin
const webpack = require("webpack")

export default {
  plugins: [new webpack.DefinePlugin({})],
}

index.js

console.log(process.env.NODE_ENV) // "development"
2.3 HtmlWebpackPlugin
new HtmlWebpackPlugin({
            title: "webpack-practice",
            template: "./index.html", // 템플릿 경로를 지정
            inject: "body",
            favicon: "./favicon.PNG"
            }),

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>
            <%= htmlWebpackPlugin.options.title %>
        </title>
    </head>
    <body>

    </body>
</html>
<title>webpack-practice</title>
2.4 MiniCssExtractPlugin
    plugins: [
        ...(process.env.NODE_ENV === "production"
        ? [new MiniCssExtractPlugin({ filename: `[name].css` })]
        : []),
    ],
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          process.env.NODE_ENV === "production"
            ? MiniCssExtractPlugin.loader // 프로덕션 환경
            : "style-loader", // 개발 환경
          "css-loader",
        ],
      },
    ],
  },
}

끝!