TypeScript、ESLint、Prettier、Babel代码规范集成

    27

以React17为例子

Babel

yarn add @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/plugin-transform-runtime -D

babel.config.json

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

Eslint

.eslintrc.json

{
    "env": {
        "browser": true,
        "es2020": true,
        "node": true
    },
    "extends": [
        "plugin:promise/recommended",
        "plugin:react/recommended",
        "plugin:react-hooks/recommended",
        "plugin:@typescript-eslint/recommended",
        "prettier/@typescript-eslint",
        "plugin:prettier/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2020,
        "sourceType": "module"
    },
    "plugins": [
        "promise",
        "react",
        "@typescript-eslint",
        "react-hooks",
        "prettier"
    ],
    "rules": {
      //0 关闭 1 警告 2 错误
        "prettier/prettier": 2,
        "react-hooks/rules-of-hooks": 2,
        "react-hooks/exhaustive-deps": 1,
        "react/display-name": 0,
        "react/prop-types":0,
        "@typescript-eslint/no-var-requires": 0
    },
    "settings": {
        "react": {
            "version": "detect"
        }
    }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "allowJs": true,
    "jsx": "react",
    "declaration": false,
    "downlevelIteration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "moduleResolution": "node",
    "baseUrl": "./src",
    "paths": {
      "api/*": ["services/*"]
    },
    "types": ["node", "webpack-env"],
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": ["config", "commitlint.config.js"]
}

.prettierrc

{
  "trailingComma": "all",
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true,
  "endOfLine": "lf",
  "printWidth": 100,
  "bracketSpacing": true,
  "arrowParens": "always",
  "useTabs": false,
  "quoteProps": "as-needed",
  "jsxSingleQuote": true,
  "jsxBracketSameLine": false,
  "requirePragma": false,
  "insertPragma": false,
  "proseWrap": "preserve",
  "htmlWhitespaceSensitivity": "css",
  "vueIndentScriptAndStyle": false,
  "embeddedLanguageFormatting": "auto"
}

lint-staged和husky

在package.json添加

{
  "husky": {
      "hooks": {
          "pre-commit": "lint-staged"
      }
  },
  "lint-staged": {
    "src/**/*.{ts,tsx,js,json,less,md}": [
      "prettier --write"
    ],
    "src/**/*.{ts,tsx,js}": [
      "eslint --config .eslintrc.json"
    ]
  }
}
评论区
共有评论 0
暂无评论