Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在项目中使用 ESLint 和 Prettier #6

Open
maomao1996 opened this issue Jun 6, 2020 · 0 comments
Open

在项目中使用 ESLint 和 Prettier #6

maomao1996 opened this issue Jun 6, 2020 · 0 comments
Labels
CLI 脚手架配置相关

Comments

@maomao1996
Copy link
Owner

maomao1996 commented Jun 6, 2020

在项目中使用 ESLint 和 Prettier(以 React + TypeScript 为例)

使用 CRA 初始化项目

npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript

使用 ESLint

安装依赖

CRA 自带了 eslint,不用额外安装

yarn add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react

配置文件 .eslintrc.js 介绍

根目录新建 .eslintrc.js 文件

module.exports = {
  // 运行环境
  env: {
    browser: true,
    es2020: true
  },
  // 继承的规则 / 插件
  extends: ['plugin:react/recommended', 'plugin:@typescript-eslint/recommended'],
  // 解析器
  parser: '@typescript-eslint/parser',
  // 解析器配置
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    },
    ecmaVersion: 2018,
    sourceType: 'module'
  },
  // 插件
  plugins: ['react', '@typescript-eslint'],
  settings: {
    // 自动检测 React 的版本
    react: {
      version: 'detect'
    }
  },
  // 规则
  rules: {
    'react/prop-types': 0,
    'react/forbid-prop-types': 0,
    'react/jsx-indent': 0
  }
}

.eslintrc.js 配置项说明

添加脚本命令

package.jsonscripts 配置项中写入 "lint": "eslint --ext js,ts,tsx src"


使用 Prettier

Prettier 是一个代码格式化工具,它通过解析代码并使用自己的规则(考虑最大行长)重新格式化代码,从而实现一致的编码风格

安装

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

修改 .eslintrc.js

eslint-config-prettier 8.0.0 之后版本

extends 配置项中增加 prettierplugin:prettier/recommended

eslint-config-prettier 8.0.0 之前版本

extends 配置项中增加 prettier/@typescript-eslintplugin:prettier/recommended

相关 CHANGELOG

自定义 Prettier 风格规则

在根目录创建 .prettierrc 文件和 .prettierignore

.prettierrc

  1. 自定义 Prettier 风格规则
{
  "singleQuote": true,
  "semi": false,
  "trailingComma": "none",
  "printWidth": 80,
  "overrides": [
    {
      "files": ".prettierrc",
      "options": { "parser": "json" }
    }
  ]
}
  1. .prettierignore

配置 Prettier 忽略文件

package.json
tsconfig.json

添加脚本命令

package.jsonscripts 配置项中写入 "fix": "prettier --write ./src"

相关资料

ESLint Rules
Prettier Options

其他

使用 husky、lint-staged、commitlint 构建前端工作流

@maomao1996 maomao1996 added the CLI 脚手架配置相关 label Mar 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CLI 脚手架配置相关
Projects
None yet
Development

No branches or pull requests

1 participant