Skip to content

plugins

박수정 edited this page Aug 15, 2024 · 7 revisions

Plugin이란?

공식 문서

플러그인(Plugin)은 웹팩의 기본적인 동작에 추가적인 기능을 제공하는 속성
로더는 파일을 해석하고 변환하는 과정에 관여하는 반면
플러그인은 해당 결과물의 형태를 바꾸는 역할을 한다.

선언

// webpack.config.js
module.exports = {
  plugins: []
}

적용 예시

플러그인의 배열에는 생성자 함수로 생성한 객체 인스턴스만 추가될 수 있다.

// webpack.config.js
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlWebpackPlugin(),
    new webpack.ProgressPlugin()
  ]
}

MiniCssExtractPlugin 플러그인의 적용

MiniCssExtractPlugin 플러그인을 적용하면 별도의 파일로 css를 분리할 수 있다.

// webpack.config.js
var path = require("path");
var MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  mode: "none", // production, development, none
  entry: "./index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [new MiniCssExtractPlugin()],
};

dist 폴더에 main.css가 생성되었음을 알 수 있다.

image


이 분리된 파일을 html에 연결시켜주는 작업이 필요하다.

image


정상 적용된 화면과 개발자 도구

image

image


html-webpack-plugin 플러그인의 적용

// webpack.config.js
var path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  mode: "none",
  entry: "./index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  devServer: {
    port: 9000,
  },
  plugins: [
    new HtmlWebpackPlugin({
      // index.html 템플릿을 기반으로 빌드 결과물을 추가해줌
      template: "index.html",
    }),
  ],
};

빌드 전 index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Webpack Dev Server</title>
    <!-- HTML Webpack Plugin에 의해 웹팩 빌드 내용이 아래에 추가됨 -->
  </head>
  <body>
  </body>
</html>

빌드 후 index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Webpack Dev Server</title>
    <!-- HTML Webpack Plugin에 의해 웹팩 빌드 내용이 아래에 추가됨 -->
    <script defer src="bundle.js"></script>
</head>
  <body>
  </body>
</html>

bundle.js가 알아서 추가되었음을 확인할 수 있다.
실제 개발 환경에서는 여러 파일 추가가 필요할 수 있고
hash값이 붙어야 하기 때문에 유용한 플러그인이다.

Clone this wiki locally