처음부터 Husky for WordPress를 사용하여 ESLint, Prettier, pre-commit 연결을 설정합니다.


저는 Eslint와 그 장점을 알고 싶습니다. 그러면 WordPress나 다른 프로젝트에서 Husky와 함께 Eslint를 설정하기 시작합니다. 더 예뻐요.
그들 모두는 한 줄이 있다.
ESLint: - ESLint는 JavaScript 프로그래밍 언어의 linter로 Node에서 작성됩니다.js.이것은 자바스크립트 코드의 문제를 발견하고 복구하는 데 도움이 됩니다.
Prettier:-Prettier는 우리가 설정한 규칙을 이용하여 코드를 포맷하는 고집스러운 코드 포맷 프로그램이다.
Husky: - Husky는 NPM 패키지로 git 작업 전에 명령이나 스크립트를 실행할 수 있습니다.egpre-push,pre-commit,pre-rebase에 대해.

1. 프로젝트에 NPM을 추가합니다.


ESLint를 실행하려면 프로젝트에 npm을 설치해야 합니다.package.json 파일이 이미 있는 경우 이 단계를 건너뛰고 프로젝트에 ESLint를 추가하는 것으로 이동할 수 있습니다.없으면 다음 절차에 따라 패키지를 만듭니다.json 파일.
항목의 루트 폴더로 이동합니다.워드프레스의 경우 테마 폴더나 테마의 자산 폴더가 될 수 있습니다.
이 명령을 실행합니다.
npm init
프로젝트에 대한 자세한 내용을 추가한 다음 루트 폴더에 package.jsonpackage-lock.json 파일을 만듭니다.

2, ESLint 설정


이 명령을 실행하면 프로젝트에 ESlint를 추가합니다.
npm install eslint --save-dev
참조 번호: https://eslint.org/docs/user-guide/getting-started
위의 명령은 프로젝트에 ESLint를 설치합니다.이제 프로젝트에 대해 ESLint 규칙과 구성을 설정합니다.우리는 사용할 것이다 eslint-config-airbnb rules.

3. Airbnb 패키지를 사용하여 ESLint 구성


이 명령을 실행합니다.
npx eslint --init
항목에 대한 자세한 정보를 추가합니다.다음 문제에 대해 다음 답을 선택하십시오.
  • "구성 파일의 형식은 무엇입니까?"-선택한 옵션에서 JSON을 선택하십시오.
  • "어떤 스타일 가이드를 따르고 싶으세요?"- 선택한 옵션에서 Airbnb를 선택하세요.
  • 이 명령을 실행합니다.
    npm i eslint-config-airbnb
    
    참조 번호: https://www.npmjs.com/package/eslint-config-airbnb

    4. ESLint 구성 파일 만들기


    모든 ESLint 규칙을 추가하기 위해 .eslintrc.json라는 파일을 만듭니다.
    모든 규칙에 대한 ESLint 구성 파일은 별도로 비활성화됩니다.
    이 파일은 Eslint 구성 파일(eslintrc.json 파일로 모든 규칙을 닫기 때문에 모든 규칙에 맞게 코드를 변경하는 것이 아니라 규칙별로 코드를 변경할 수 있습니다.
    여기서 규칙을 복사하여 닫기 - https://eslint.org/docs/rules/
    파일 이름 - .eslintrc.json
    {
      "env": {
        "browser": true
      },
     "extends": ["airbnb-base", "plugin:prettier/recommended"],
      "plugins": ["prettier"],
      "rules": {
        // disable es6 rules -- start
        "arrow-body-style": "off",
        "arrow-parens": "off",
        "arrow-spacing": "off",
        "constructor-super": "off",
        "generator-star-spacing": "off",
        "no-class-assign": "off",
        "no-confusing-arrow": "off",
        "no-const-assign": "off",
        "no-dupe-class-members": "off",
        "no-duplicate-imports": "off",
        "no-new-symbol": "off",
        "no-restricted-imports": "off",
        "no-this-before-super": "off",
        "no-useless-computed-key": "off",
        "no-useless-constructor": "off",
        "no-useless-rename": "off",
        "no-var": "off",
        "object-shorthand": "off",
        "prefer-arrow-callback": "off",
        "prefer-const": "off",
        "prefer-destructuring": "off",
        "prefer-numeric-literals": "off",
        "prefer-reflect": "off",
        "prefer-rest-params": "off",
        "prefer-spread": "off",
        "prefer-template": "off",
        "require-yield": "off",
        "rest-spread-spacing": "off",
        "sort-imports": "off",
        "symbol-description": "off",
        "template-curly-spacing": "off",
        "yield-star-spacing": "off",
        // disable es6 rules -- end
    
        // Possible Errors -- start
        "for-direction": "off",
        "getter-return": "off",
        "no-async-promise-executor": "off",
        "no-await-in-loop": "off",
        "no-compare-neg-zero": "off",
        "no-cond-assign": "off",
        "no-console": "off",
        "no-constant-condition": "off",
        "no-control-regex": "off",
        "no-debugger": "off",
        "no-dupe-args": "off",
        "no-dupe-else-if": "off",
        "no-dupe-keys": "off",
        "no-duplicate-case": "off",
        "no-empty": "off",
        "no-empty-character-class": "off",
        "no-ex-assign": "off",
        "no-extra-boolean-cast": "off",
        "no-extra-parens": "off",
        "no-extra-semi": "off",
        "no-func-assign": "off",
        "no-import-assign": "off",
        "no-inner-declarations": "off",
        "no-invalid-regexp": "off",
        "no-irregular-whitespace": "off",
        "no-loss-of-precision": "off",
        "no-misleading-character-class": "off",
        "no-obj-calls": "off",
        "no-promise-executor-return": "off",
        "no-prototype-builtins": "off",
        "no-regex-spaces": "off",
        "no-setter-return": "off",
        "no-sparse-arrays": "off",
        "no-template-curly-in-string": "off",
        "no-unexpected-multiline": "off",
        "no-unreachable": "off",
        "no-unreachable-loop": "off",
        "no-unsafe-finally": "off",
        "no-unsafe-negation": "off",
        "no-useless-backreference": "off",
        "require-atomic-updates": "off",
        "use-isnan": "off",
        "valid-typeof": "off",
        // Possible Errors -- end
    
        // Best Practices -- start
        "accessor-pairs": "off",
        "array-callback-return": "off",
        "block-scoped-var": "off",
        "class-methods-use-this": "off",
        "complexity": "off",
        "consistent-return": "off",
        "curly": "off",
        "default-case": "off",
        "default-case-last": "off",
        "default-param-last": "off",
        "dot-location": "off",
        "dot-notation": "off",
        "eqeqeq": "off",
        "grouped-accessor-pairs": "off",
        "guard-for-in": "off",
        "max-classes-per-file": "off",
        "no-alert": "off",
        "no-caller": "off",
        "no-case-declarations": "off",
        "no-constructor-return": "off",
        "no-div-regex": "off",
        "no-else-return": "off",
        "no-empty-function": "off",
        "no-empty-pattern": "off",
        "no-eq-null": "off",
        "no-eval": "off",
        "no-extend-native": "off",
        "no-extra-bind": "off",
        "no-extra-label": "off",
        "no-fallthrough": "off",
        "no-floating-decimal": "off",
        "no-global-assign": "off",
        "no-implicit-coercion": "off",
        "no-implicit-globals": "off",
        "no-implied-eval": "off",
        "no-invalid-this": "off",
        "no-iterator": "off",
        "no-labels": "off",
        "no-lone-blocks": "off",
        "no-loop-func": "off",
        "no-magic-numbers": "off",
        "no-multi-spaces": "off",
        "no-multi-str": "off",
        "no-new": "off",
        "no-new-func": "off",
        "no-new-wrappers": "off",
        "no-octal": "off",
        "no-octal-escape": "off",
        "no-param-reassign": "off",
        "no-proto": "off",
        "no-redeclare": "off",
        "no-restricted-properties": "off",
        "no-return-assign": "off",
        "no-return-await": "off",
        "no-script-url": "off",
        "no-self-assign": "off",
        "no-self-compare": "off",
        "no-sequences": "off",
        "no-throw-literal": "off",
        "no-unmodified-loop-condition": "off",
        "no-unused-expressions": "off",
        "no-unused-labels": "off",
        "no-useless-call": "off",
        "no-useless-catch": "off",
        "no-useless-concat": "off",
        "no-useless-escape": "off",
        "no-useless-return": "off",
        "no-void": "off",
        "no-warning-comments": "off",
        "no-with": "off",
        "prefer-named-capture-group": "off",
        "prefer-promise-reject-errors": "off",
        "prefer-regex-literals": "off",
        "radix": "off",
        "require-await": "off",
        "require-unicode-regexp": "off",
        "vars-on-top": "off",
        "wrap-iife": "off",
        "yoda": "off",
        // Best Practices -- end
    
        // Strict Mode -- start
        "strict": "off",
        // Strict Mode -- end
    
        // Variables -- start
        "init-declarations": "off",
        "no-delete-var": "off",
        "no-label-var": "off",
        "no-restricted-globals": "off",
        "no-shadow": "off",
        "no-shadow-restricted-names": "off",
        "no-undef": "off",
        "no-undef-init": "off",
        "no-undefined": "off",
        "no-unused-vars": "off",
        "no-use-before-define": "off",
        // Variables -- end
    
        // Stylistic Issues -- start
        "array-bracket-newline": "off",
        "array-bracket-spacing": "off",
        "array-element-newline": "off",
        "block-spacing": "off",
        "brace-style": "off",
        "camelcase": "off",
        "capitalized-comments": "off",
        "comma-dangle": "off",
        "comma-spacing": "off",
        "comma-style": "off",
        "computed-property-spacing": "off",
        "consistent-this": "off",
        "eol-last": "off",
        "func-call-spacing": "off",
        "func-name-matching": "off",
        "func-names": "off",
        "func-style": "off",
        "function-call-argument-newline": "off",
        "function-paren-newline": "off",
        "id-denylist": "off",
        "id-length": "off",
        "id-match": "off",
        "implicit-arrow-linebreak": "off",
        "indent": "off",
        "jsx-quotes": "off",
        "key-spacing": "off",
        "keyword-spacing": "off",
        "line-comment-position": "off",
        "linebreak-style": "off",
        "lines-around-comment": "off",
        "lines-between-class-members": "off",
        "max-depth": "off",
        "max-len": "off",
        "max-lines": "off",
        "max-lines-per-function": "off",
        "max-nested-callbacks": "off",
        "max-params": "off",
        "max-statements": "off",
        "max-statements-per-line": "off",
        "multiline-comment-style": "off",
        "multiline-ternary": "off",
        "new-cap": "off",
        "new-parens": "off",
        "newline-per-chained-call": "off",
        "no-array-constructor": "off",
        "no-bitwise": "off",
        "no-continue": "off",
        "no-inline-comments": "off",
        "no-lonely-if": "off",
        "no-mixed-operators": "off",
        "no-mixed-spaces-and-tabs": "off",
        "no-multi-assign": "off",
        "no-multiple-empty-lines": "off",
        "no-negated-condition": "off",
        "no-nested-ternary": "off",
        "no-new-object": "off",
        "no-plusplus": "off",
        "no-restricted-syntax": "off",
        "no-tabs": "off",
        "no-ternary": "off",
        "no-trailing-spaces": "off",
        "no-underscore-dangle": "off",
        "no-unneeded-ternary": "off",
        "no-whitespace-before-property": "off",
        "nonblock-statement-body-position": "off",
        "object-curly-newline": "off",
        "object-curly-spacing": "off",
        "object-property-newline": "off",
        "one-var": "off",
        "one-var-declaration-per-line": "off",
        "operator-assignment": "off",
        "operator-linebreak": "off",
        "padded-blocks": "off",
        "padding-line-between-statements": "off",
        "prefer-exponentiation-operator": "off",
        "prefer-object-spread": "off",
        "quote-props": "off",
        "quotes": "off",
        "semi": "off",
        "semi-spacing": "off",
        "semi-style": "off",
        "sort-keys": "off",
        "sort-vars": "off",
        "space-before-blocks": "off",
        "space-before-function-paren": "off",
        "space-in-parens": "off",
        "space-infix-ops": "off",
        "space-unary-ops": "off",
        "spaced-comment": "off",
        "switch-colon-spacing": "off",
        "template-tag-spacing": "off",
        "unicode-bom": "off",
        "wrap-regex": "off"
        // Stylistic Issues -- end
      }
    }
    

    5. ESLint 무시 파일 만들기


    참조 - https://eslint.org/docs/user-guide/configuring#ignorepatterns-in-config-files.eslintignore라는 파일을 만듭니다. 이 파일은 특정 파일이나 폴더를 무시하는 규칙을 추가하는 데 사용됩니다.
    지금 나는 단지 소홀히 했을 뿐이다node_modules folder.필요에 따라 새 규칙을 사용자 정의하고 추가할 수 있습니다.
    파일 이름 - .eslintignore
    node_modules/**
    

    6, ESLint와 함께 Prettier 추가


    ESLint를 사용하여 prettier-https://prettier.io/docs/en/install.html 추가
    다음 명령을 실행하여prettier를 설치합니다
    npm install --save-dev --save-exact prettier
    npm install --save-dev eslint-config-prettier eslint-plugin-prettier
    
    전자는 Prettier와 충돌할 수 있는 모든 ESLint 규칙을 닫고, 후자는 Prettier 규칙을 ESLint 규칙에 집적합니다.
    파일 이름 - .prettierrc
    {
      "semi": true,
      "trailingComma": "es5",
      "printWidth": 120,
      "singleQuote": true,
      "arrowParens": "always",
      "proseWrap": "preserve"
    }
    

    7. Prettier ignore 파일 추가

    .prettierignore 파일에는 더 예쁜 검사에서 무시해야 할 파일 목록이 포함되어 있습니다.
    파일 이름 - .prettierignore
    node_modules/**
    
    # Ignore all JS files:
    **/*.js
    
    현재, 나는 모든 js 파일과 node_modules 폴더를 무시했다.

    만세!우리는 현재 우리의 프로젝트를 위해 ESLint+Prettier를 설치했다.

    파일에서 ESLint 오류를 확인하는 데 사용되는 명령입니다.


    단일 js 파일에 대해
    npx eslint js/amplitude.js --format table
    
    여러 js 파일에 동시에 사용
    npx eslint **/*.js --format table
    

    VSCode에서 ESlint 및 더 멋진 플러그인을 구성합니다.


    저희 프로젝트에는 ESLint와 더 예쁜 프로필이 있기 때문에 VSCode 편집기 플러그인은 로컬 프로필만 사용합니다.
    ESLint Plugin
    Prettier Plugin

    8. Husky를 사용하여 사전 제출 갈고리 검사


    Husky를 사전 제출 연결과 함께 사용하도록 설정하고 linting 오류가 있는지 확인합니다.
    Husky를 설치하려면
    npm install husky --save-dev
    npm install --save-dev lint-staged
    
    package.json 파일에 Husky 사전 제출 구성 추가package.json 파일에husky 설정 추가
    "husky": {
        "hooks": {
          "pre-commit": "lint-staged"
        }
      },
      "lint-staged": {
        "**/*.js": [
          "eslint --fix",
          "git add"
        ]
      },
    
    언제든지 변경 사항을 제출하고 js 파일을 포함하면 Husky는 이 파일들이 모든 linting 요구에 부합되는지 확인합니다.만약 없다면, 그것은 너로 하여금 이 문제들을 해결하지 않는 한 약속을 하게 하지 않을 것이다.
    이것이 바로 성공한 하스키의 수표 모습이다.

    9. 최종 포장.json 파일


    이것은 나의 package.json 파일이 상술한 모든 절차를 집행한 후의 모습이다.
    파일 이름 - package.json
    {
      "name": "twentyseventeen",
      "version": "1.0.0",
      "description": "=== Twenty Seventeen === Contributors: wordpressdotorg Tested up to: 5.5 Version: 2.4 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: one-column, two-columns, right-sidebar, flexible-header, accessibility-ready, custom-colors, custom-header, custom-menu, custom-logo, editor-style, featured-images, footer-widgets, post-formats, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready",
      "main": "index.js",
      "husky": {
        "hooks": {
          "pre-commit": "lint-staged"
        }
      },
      "lint-staged": {
        "**/*.js": [
          "eslint --fix",
          "git add"
        ]
      },
      "dependencies": {
        "eslint-config-airbnb": "^18.2.0"
      },
      "devDependencies": {
        "eslint": "^7.11.0",
        "eslint-config-airbnb-base": "^14.2.0",
        "eslint-config-prettier": "^6.12.0",
        "eslint-plugin-import": "^2.22.1",
        "eslint-plugin-prettier": "^3.1.4",
        "husky": "^4.3.0",
        "lint-staged": "^10.4.0",
        "prettier": "2.1.2"
      },
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
    

    좋은 웹페이지 즐겨찾기