optimization

[Webpack + opt] css 최적화

개발가락 2023. 4. 25. 18:13

 

Intro.

배포 환경에선 당연히 더 나은 UX를 위해 번들 사이즈를 줄여야합니다.

이번 글에선 webpack 번들링 과정에서 css 파일들을 어떤식으로 최적화 할 수 있을지 이야기 해보겠습니다.

 

Index

1. CSS 압축

before -> after

2. 코멘트 제거

before -> after

 

3. 안쓰는 CSS 제거

 

 

이렇게 크게 3가지 방법이 있습니다.

 

 

Method

  • CSS 압축 & comment 제거 1. CSSMinimizerPlugin을 설치합니다. 

       해당 플러그인은 기본적으로 CSS Nano 와 동작방식이 같습니다.

 

yarn add -D css-minimizer-webpack-plugin

       2. config파일 내, optimization 객체에 해당 플러그인을 추가합니다.

module.exports = merge(common, {
  ...,
  optimization: {
    minimize: true,
    minimizer: [
      '...', // 만약, 개발 및 배포 환경이 나뉠 시, common config파일에 다른 플러그인이 추가되어있을 경우, 좌측 키워드를 통해 유지할 수 있습니다.
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: [
            'default',
            {
              discardComments: { //해당 프로퍼티 추가로 모든 코멘트들을 지웁니다.
                removeAll: true  
              }
            }
          ]
        }
      })
    ]
  },

만약 CSSNano외에 다른 필터링 알고리즘을 사용하고 싶으시다면, 아래와 같이 지정 할 수 있습니다.

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.cssoMinify,
      }),
    ],
  },
};

 

CSSMinimizerPlugin의 가능한 최적화 옵션은 아래 링크에서 참조가능합니다.

https://cssnano.co/docs/what-are-optimisations/ 

 

Optimisations/

CSSNANO - postcss based css optimizer

cssnano.co

 

 

  • 안쓰는 CSS 제거

           1. purgecss-webpack-plugin을 설치합니다. (해당 모듈 공식 문서에서 glob, path 모듈을 유틸로 쓰기에 같이 설치해주겠습니                다.)

yarn add -D purgecss-webpack-plugin glob path

         

            2. webpack 설정에 해당 플러그인을 추가합니다.

module.exports = {
	...,
   plugins: [
	..., //other plugins
    new PurgeCSSPlugin({
      paths: glob.sync(`${path.join(__dirname, '../src')}/**/*`, {
        nodir: true, // 디렉토리는 제외합니다 (안그러면 디렉토리 삭제됩니다.),
       	fontface: true, //안쓰는 폰트 제거
        keyframes: true, // 안쓰는 애니메이션 키프레임 제거
        variables: true // 안쓰는 css 변수 제거
      })
    })
  ]
}

 

사용가능한 옵션은 아래에서 참조가능합니다. ( 단 css, content 속성은 사용불가)

https://purgecss.com/configuration.html

 

Configuration | PurgeCSS

Configuration PurgeCSS has a list of options that allow you to customize its behavior. Customization can improve the performance and efficiency of PurgeCSS. You can create a configuration file with the following options. Configuration file The configuratio

purgecss.com