본문 바로가기

Bundler

[Webpack] CSS 파일 메인 번들과 분리시키기 (MiniCssExtractPlugin)

 

Intro.

style-loader를 통한 css번들링의 단점은, css 규칙이 메인 번들에 포함된다는 점입니다. 즉, 가만 납두면 번들 하나의 사이즈가 매우 커진다는 의미지요. 게다가 css의 주입이 런타임에 일어나는 것 또한 문제입니다. 개발환경에선 상관 없을지도 모르겠으나, 배포용 환경에선 문제가 많을 것 같습니다. 일단 번들 하나의 사이즈가 커진다면, 당연히 그만큼 다운로드 받는데 오래걸릴테고 이는 곧 UX저하로 이어지겠지요. 따라서 적어도 스크립트와 CSS는 분리하여 번들링하는게 좋을 듯 합니다.

 

 

Goal

 

Before

after

 

Method

1. mini-css-extract-plugin을 설치합니다.

 

yarn add -D mini-css-extract-plugin

 

2. config파일에 css 번들링 rule을 수정합니다.

 

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const config = {
  entry: '/src/js/index',
  module: {
      rules: [
         {
          test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader']
          }
        ]
  },
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].[contenthash:12].js'
  }
};

module.exports = config;

 

3. MiniCssExtractPlugin을 config파일의 plugin으로써 등록합니다.

 

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const config = {
  entry: '/src/js/index',
  module: {
      rules: [
         {
          test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader']
          }
        ]
  },
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].[contenthash:12].js'
  },
   plugins: [
    new MiniCssExtractPlugin({
      filename: 'name-of-file' //e.g 'style.css
      //저같은 경우 다음과 같이 지정했습니다.
      //'[name].[contenthash:12].css' // base css파일 이름. 해시값 12자리.css
    })
  ]
};

module.exports = config;