Languages/CSS

[CSS] PostCSS란? / Webpack과 사용법, 플러그인 추천

MOONCO 2021. 4. 12. 17:05

PostCSS란?

CSS 후처리기이며, CSS 작성을 더 편하게 만들어주는 javascript 도구들(Plugins)이다.

javascript를 이용해서, CSS를 변경해준다

 

전처리기란?

 

[CSS] CSS 전,후 처리기란? / 비교

CSS 전,후 처리기란? CSS 작성을 도와주는 프로그램 CSS 전,후 처리기의 필요성 CSS를 작성할 때 발생하는 여러 번거로움을 줄여준다! ( ex : 중복제거, 유지보수 등등 ) CSS 전,후 처리기들 전처리기 : S

defineall.tistory.com

 

PostCSS 공식사이트

 

PostCSS - a tool for transforming CSS with JavaScript

Enforce consistent conventions and avoid errors in your stylesheets with stylelint, a modern CSS linter. It supports the latest CSS syntax, as well as CSS-like syntaxes, such as SCSS.

postcss.org

 

PostCSS 설치하기

npm install -D postcss postcss-loader

 

PostCSS 사용하기 ( Webpack사용 / Webpack이란? )

//  webpack.config.js

const path = require('path');

module.exports = {
    entry: {
        app: ["./src/index.js", "./src/test.js"]
    },
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, 'build')
    },
    mode: 'none',
    
    module: {
        rules: [
            {
                test: /\.p?css$/,  //css 파일을 선택하는 정규표현식
                use: [
                    {loader: "style-loader"},
                    {loader: "css-loader"},
                    {loader: "postcss-loader"}  // postcss 적용하기
                ],
            }
        ]
    },
};

 


PostCSS 플러그인 설치하기

npm install -D <플러그인>

 

PostCSS 플러그인 적용

// postcss.config.js

module.exports = {
    parser: 'postcss-scss', // 파서 옵션을 설정하고 싶다면 여기에서
    plugins: {
        <플러그인>: {},
        ...
    },
};

 

PostCSS 플러그인 적용시 주의사항

위에서 부터 아래로 실행하기 때문에, 플러그인 실행순서가 중요하다!

( 플러그인 github의 Readme.md를 잘 읽어야 합니다 )

 


PostCSS 플러그인 추천

autoprefixer

-webkit- 등의 prefix 없이 스타일을 지정할 수 있다.

사용 전

a {
    display: flex;
}

사용 후

a {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex
}

 

postcss-preset-env

css 내부 변수 및 중첩 css 사용가능

사용 전

root {
  --mainColor: #12345678;
}

body {
  color: var(--mainColor);
  font-family: system-ui;
}

a {
  color: rgb(0 0 100% / 90%);

  &:hover {
    color: rebeccapurple;
  }

  > span {
    font-weight: bold;
  }
}

:is(input, button):is(:hover, :focus) {
  color: oklch(40% 0.268735435 34.568626);
}

사용 후

:root {
  --mainColor: rgba(18,52,86,0.47059);
}

body {
  color: rgba(18,52,86,0.47059);
  color: var(--mainColor);
  font-family: system-ui,
              -apple-system,
              Segoe UI,
              Roboto,
              Ubuntu,
              Cantarell,
              Noto Sans,
              sans-serif;
}

a {
  color: rgba(0, 0, 255, 0.9)
}

a:hover {
    color: #639;
  }

a > span {
    font-weight: bold;
  }

input:hover, input:focus, button:hover, button:focus {
  color: rgb(143, 0, 0);
  color: color(display-p3 0.52929 0.00000 0.00000);
}

 

stylelint

css 문법 검사 해줌 ㅎㅎ
 

Home | Stylelint

npm version

stylelint.io

 

postcss-import

css @import 문법을 사용할 수 있음

/* foo.css */
.foo {
  width: 100px;
}



/* bar.css */
.bar {
  height: 20px;
}



/* index.css */
@import "foo.css";
@import "bar.css";

스타일 변환 결과

.foo {
  width: 100px;
}
.bar {
  height: 20px;
}

 

postcss-for

: for 문법을 사용할 수 있음

@for $i from 1 to 3 {
    .icon-$(i) { background-position: 0 calc($(i) * 20px); }
}

스타일 변환 결과

.icon-1 { background-position: 0 calc(1 * 20px); }
.icon-2 { background-position: 0 calc(2 * 20px); }
.icon-3 { background-position: 0 calc(3 * 20px); }

 

postcss-assets

url() 안에 들어가는 파일의 경로를 편리하게 작성, 이미지 사이즈 측정, 가져오기 가능

사용 전

body {
  background: resolve('bg.png');
}
.warn {
  width: width('warn.png'); /* calculate image size */
  background: resolve('warn.png');
}

사용 후

body {
  background: url('/images/bg.png');
}
.warn {
  width: 320px;
  background: url('/images/template/warn.png');
}

 

cssnano

css 파일을 최적화시켜줌! ( 용량 줄음 )
- 공백 제거, 여러 기능 상승
 

/

CSSNANO - postcss based css optimizer

cssnano.co

사용 전

/* normalize selectors */
h1::before, h1:before {
    /* reduce shorthand even further */
    margin: 10px 20px 10px 20px;
    /* reduce color values */
    color: #ff0000;
    /* remove duplicated properties */
    font-weight: 400;
    font-weight: 400;
    /* reduce position values */
    background-position: bottom right;
    /* normalize wrapping quotes */
    quotes: '«' "»";
    /* reduce gradient parameters */
    background: linear-gradient(to bottom, #ffe500 0%, #ffe500 50%, #121 50%, #121 100%);
    /* replace initial values */
    min-width: initial;
}
/* correct invalid placement */
@charset "utf-8";

사용후

@charset "utf-8";h1:before{margin:10px 20px;color:red;font-weight:400;background-position:100% 100%;quotes:"«" "»";background:linear-gradient(180deg,#ffe500,#ffe500 50%,#121 0,#121);min-width:0}
반응형