LIGHTLOG

Why stylelint?

✅ 협업을 하다보면 팀원 각자만의 퍼블리싱 스타일, 즉 css 속성을 작성하는 규칙이 매우 다릅니다. 따라서, css 코드에 일관성을 주고 가독성을 높여주기 위함입니다.

✅ 디자인 변경이나 개선을 할 때, 시간을 줄여줄 수 있습니다. 


stylelint 적용하기

 

Home | Stylelint

npm version

stylelint.io

라이브러리 설치

우선, 각자 환경(npm/yarn)에서 필요한 라이브러리를 설치해주세요.

저는 아래 4가지만 devDependencies에 설치했습니다.

stylelint <- stylint 사용을 위해 설치해야할 기본 패키지이다.
stylelint-order <- css 속성 정렬을 위한 패키지이다. 
stylelint-config-standard <- 기본 추천되는 CSS 사양에 있는 최신 규칙을 적용하기 위한 패키지이다.
postcss-styled-syntax <- 템플릿 리터럴 CSS-in-JS(ex. styled-component)인 styled로 작성된 CSS 속성들을 파싱해주는 패키지이다.

 

 

스크립트 작성

"scripts": {
    ...
    "lint:css": "stylelint --ignore-path .gitignore './src/**/*.tsx' --fix",
  },

 

package.json에 위의 script를 추가해줍니다.

--ignore-path .gitignore는 .gitignore 상에 해당되는 파일들은 검사를 하지 않겠다는 의미같습니다. 

--fix 옵션을 주면 스크립트를 실행해줄 때마다, css 속성이 일관되게 수정됩니다.

 

그밖에 다른 옵션들도 많으니, 목적에 맞게 스크립트를 커스텀해두시는 것을 추천드려요.

A mighty CSS linter that helps you avoid errors and enforce conventions.

  Usage: stylelint [input] [options]

  Input: Files(s), glob(s), or nothing to use stdin.

    If an input argument is wrapped in quotation marks, it will be passed to
    globby for cross-platform glob support. "node_modules" are always ignored.
    You can also pass no input and use stdin, instead.

  Options:

    --config, -c <path_or_module>

      A path to a specific configuration file (JSON, YAML, CommonJS, or ES module),
      or a module name in "node_modules" that points to one. If no argument is
      provided, Stylelint will search for configuration files in the following
      places, in this order:

        - a "stylelint" property in "package.json"
        - a ".stylelintrc" file
        - a ".stylelintrc.{cjs,mjs,js,json,yaml,yml}" file
        - a "stylelint.config.{cjs,mjs,js}" file

      The search will begin in the working directory and move up the directory
      tree until a configuration file is found.

    --config-basedir <path>

      An absolute path to the directory that relative paths defining "extends",
      "plugins", and "customSyntax" are *relative to*. Only necessary if these
      values are relative paths.

    --print-config

      Print the configuration for the given input file path. Globs are unsupported.

    --ignore-path, -i <path>

      A path to a file containing patterns that describe files to ignore. The
      path can be absolute or relative to "process.cwd()". You can repeat the
      option to provide multiple paths. By default, Stylelint looks for
      ".stylelintignore" in "process.cwd()". Multiple can be set.

    --ignore-pattern, --ip <pattern>

      A pattern of files to ignore (in addition to those in ".stylelintignore").
      Multiple can be set.

    --fix

      Automatically fix problems of certain rules.

    --custom-syntax <name_or_path>

      A module name or path to a JS file exporting a PostCSS-compatible syntax.

    --stdin

      Accept stdin input even if it is empty.

    --stdin-filename <name>

      A filename to assign stdin input.

    --ignore-disables, --id

      Ignore "stylelint-disable" comments.

    --disable-default-ignores, --di

      Allow linting of "node_modules".

    --[no-]cache

      Store the info about processed files in order to only operate on the
      changed ones the next time you run Stylelint. By default, the cache is
      stored in "./.stylelintcache". To adjust this, use "--cache-location".
      Cache is disabled by default.

    --cache-location <path>

      A path to a file or directory to be used for the cache location. If a
      directory is specified, a cache file will be created inside the specified
      folder, with a name derived from a hash of the current working directory.

      If the directory for the cache does not exist, make sure you add a trailing "/"
      on *nix systems or "\" on Windows. Otherwise the path will be assumed to
      be a file.

    --cache-strategy <strategy>

      A strategy for the cache to use for detecting changed files. Either one of:

        metadata     by metadata of a file (default)
        content      by content of a file

      The "content" strategy can be useful in cases where the modification time
      of your files changes even if their contents have not. For example, this can
      happen during git operations like "git clone" because git does not track file
      modification time.

    --formatter, -f <formatter>

      An output formatter. The variants are as follows:

        string       human-readable strings (default)
        compact      similar to ESLint's compact formatter
        github       workflow commands for GitHub Actions
        json         JSON format
        tap          TAP format
        unix         C compiler-like format
        verbose      extend "string" to include a file list and a tally

    --custom-formatter <path_or_module>

      A path to a JS file or module name exporting a custom formatting function.

    --quiet, -q

      Only register problems for rules with an "error"-level severity (ignore
      "warning"-level).

    --quiet-deprecation-warnings

      Ignore deprecations warnings.

    --[no-]color

      Force enabling/disabling of color.

    --report-needless-disables, --rd

      Also report errors for "stylelint-disable" comments that are not blocking
      a lint warning. The process will exit with code 2 if needless disables are found.

    --report-invalid-scope-disables, --risd

      Report "stylelint-disable" comments that used for rules that don't exist
      within the configuration object. The process will exit with code 2 if invalid
      scope disables are found.

    --report-descriptionless-disables, --rdd

      Report "stylelint-disable" comments without a description. The process will
      exit with code 2 if descriptionless disables are found.

    --max-warnings, --mw <number>

      The number of warnings above which the process will exit with code 2.
      Useful when setting "defaultSeverity" to "warning" and expecting the process
      to fail on warnings (e.g. CI build).

    --output-file, -o <path>

      A file path to write a report.

    --allow-empty-input, --aei

      When a glob pattern matches no files, the process will exit without throwing an error.

    --globby-options, --go <json>

      Options in JSON format passed to globby.

    --version, -v

      Show the version.

    --help, -h

      Show the help.

✨  Done in 0.78s.

 

 

.stylelintrc

제가 설정해준 규칙과 적용방법은 다음과 같습니다!

저는 애초에 stylelint를 해야겠다고 마음먹은 이유가 바로 '정렬' 때문이었습니다.

퍼블리싱을 하다보면 마구잡이로 속성들을 나열하게 되면서 중복 속성이 생긴다던지 순서가 뒤죽박죽 되서

추후에 리팩터링이나 중복된 디자인 코드 추출에도 어렵더라구요.

 

따라서 stylelint-order를 깔았고 -> ("plugins": ["stylelint-order"])

그룹에 맞게 정렬되게끔 -> ("order/properties-order")

해주었습니다. 

 

emptyLineBefore: "always"를 해준 이유는, 그룹별로 개행을 하기 위해서 입니다.

하지만!

"declaration-empty-line-before": null 로 stylelint-config-standard의 옵션을 disable 해주어야만 가능합니다. (stylelint-config-standard의 기본 옵션은 css에서 개행을 다 검열해서 삭제해버리기 때문.)

{
  "extends": ["stylelint-config-standard"],
  "plugins": ["stylelint-order"],
  "rules": {
    "declaration-empty-line-before": null,
    "order/properties-order": [
      {
        "groupName": "layout",
        "properties": [
          "display",
          "box-sizing",
          "float",
          "width",
          "height",
          "max-width",
          "max-height",
          "min-width",
          "min-height",
          "padding",
          "padding-top",
          "padding-right",
          "padding-bottom",
          "padding-left",
          "margin",
          "margin-top",
          "margin-right",
          "margin-bottom",
          "margin-left",
          "margin-collapse",
          "margin-top-collapse",
          "margin-right-collapse",
          "margin-bottom-collapse",
          "margin-left-collapse",
          "overflow",
          "overflow-x",
          "overflow-y",
          "clip",
          "clear"
        ]
      },
      {
        "groupName": "flexible",
        "emptyLineBefore": "always",
        "properties": [
          "flex-flow",
          "flex-direction",
          "flex-wrap",
          "justify-content",
          "align-items",
          "align-content",
          "order",
          "flex",
          "flex-grow",
          "flex-shrink",
          "flex-basis",
          "align-self"
        ]
      },
      {
        "groupName": "layout-style",
        "emptyLineBefore": "always",
        "properties": [
          "background",
          "background-color",
          "border",
          "border-radius",
          "border-color",
          "border-top",
          "border-right",
          "border-bottom",
          "border-left",
          "box-shadow"
        ]
      },
      {
        "groupName": "position",
        "emptyLineBefore": "always",
        "properties": ["position", "top", "right", "bottom", "left", "z-index"]
      },
      {
        "groupName": "font",
        "emptyLineBefore": "always",
        "properties": ["color", "font-size", "font-weight"]
      },
      {
        "groupName": "animation",
        "emptyLineBefore": "always",
        "properties": ["transition", "animation"]
      }
    ]
  },
  "customSyntax": "postcss-styled-syntax"
}

 

Before & After

명령문 한 번이면,

// 이랬던 코드가
const StyledButton = styled.button`
  height: 100px;
  padding: 5%;
  border-color: red;
  top: 5;
  width: 200px;
  height: 200px;
  color: blue;
  font-size: 15px;
  display: flex;
`;

// 이렇게
const StyledButton = styled.button`
  display: flex;
  width: 200px;
  height: 100px;
  padding: 5%;

  border-color: red;

  top: 5;

  color: blue;
  font-size: 15px;
`;

 

편~~안!

profile

LIGHTLOG

@lightOnCoding

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!