React17+Hook+TS4+VSCode开发环境搭建(2021)

前言

本文将会⽤Create-React-App初始化项⽬。并配置eslint检验代码质量,prettier代码格式化,commitlint检验提交信息,使得⼯程规范化。


一、用 Create React App 初始化项目

1、首先确保本机安装了Node.js
2、在终端窗口输入如下命令: 因为项目用到了typescript,所以后面加上这个参数,否则创建的项目是javascript版本的。

npx create-react-app csdn-admin --template typescript

二、配置 ESLint、 prettier 和 commitlint 规范工程

这里用VSCode为例,为了让这eslint、prettier和EditConfig和平相处,不发生冲突。如果不注意的话,可能会出现这样的情况,格式化完代码后,保存文件时,代码又进行了一次排版,如下:
冲突示例

这几个工具的作用

ESLint

代码质量的检查,它的目标是保证代码的一致性和避免错误。

Prettier

格式化代码的工具

commitlint

规范git提交代码的描述格式

准备开始

  • 安装配置 ESLint
  • 安装配置 Prettier
  • 检查安装过的文件
  • 解决ESLint和Prettier的冲突
  • 安装配置commitlint

1、安装配置ESLint

第一步、从React项目中移除默认的ESLint配置

默认创建的React项目自带ESLint配置,先删除掉,我们将配置更好的选项。打开package.json文件,删除下面的代码

"eslintConfig": {
   "extends":[
      "react-app",
      "react-app/jest"
   ]
}
第二步、安装 ESLint package

打开终端,在项目目录下,运行如下命令,yarn方式或npm方式安装,选择其中一种,个人推荐使用yarn。

yarn add eslint -D

npm install eslint --save-dev

安装完成后,可以在package.json文件中看到:

"devDependencies": {
        "eslint": "^7.28.0"
}

(版本可能不一致,可以忽略这个问题)

第三步、配置 ESLint

打开终端,在项目目录下,运行如下命令:

npx eslint --init

运行此命令时,您需要回答有关配置的一些问题:

How would you like to use ESLint?
选择: To check syntax, find problems, and enforce code style
What type of modules does your project use?
选择:JavaScript modules (import/export)
Which framework does your project use?
选择:React
Does your project use TypeScript?
选择:Yes
Where does your code run?
选择:Browser
How would you like to define a style for your project?
选择:Use a popular style guide
Which style guide do you want to follow?
选择:Airbnb: https://github.com/airbnb/javascript
What format do you want your config file to be in?
选择:JSON

之后,它将检查需要安装的依赖项,然后询问:

Would you like to install them now with npm?
选择: Yes

然后,它将安装所需的所有软件包。安装过程完成后,package.json文件上的devDependencies应如下所示:

"devDependencies": {
        "@typescript-eslint/eslint-plugin": "^4.26.1",
        "@typescript-eslint/parser": "^4.26.1",
        "eslint": "^7.28.0",
        "eslint-config-airbnb": "^18.2.1",
        "eslint-plugin-import": "^2.23.4",
        "eslint-plugin-jsx-a11y": "^6.4.1",
        "eslint-plugin-react": "^7.24.0",
        "eslint-plugin-react-hooks": "^4.2.0"
    }

如果版本与上述示例不匹配,可以忽略。

第四步、运行命令
npx eslint src/* 

出现了35个错误:

✖ 35 problems (35 errors, 0 warnings)
  13 errors and 0 warnings potentially fixable with the `--fix` option.

试着让它自动修复一下:

npx eslint src/* --fix

仍然出现了22个错误

✖ 22 problems (22 errors, 0 warnings)

现在来完成剩下的配置,以便我们可以正确地使用ESLint。

第五步、解决遗留问题

安装eslint-import-resolver-typescript

yarn add eslint-import-resolver-typescript -D

或者

npm install eslint-import-resolver-typescript --save-dev
  • 打开eslintrc.json文件,rules节点内增加:
"rules": {
        "no-use-before-define": "off",
        "@typescript-eslint/no-use-before-define": ["error"],
        "react/jsx-filename-extension": ["warn", { "extensions": [".tsx"] }],
        "import/extensions": [
            "error",
            "ignorePackages",
            {
                "ts": "never",
                "tsx": "never"
            }
        ],
        "no-shadow": "off",
        "@typescript-eslint/no-shadow": ["error"],        
        "max-len": ["warn", { "code": 80 }],
        "react-hooks/rules-of-hooks": "error",
        "react-hooks/exhaustive-deps": "warn",
        "import/prefer-default-export": "off",
        "react/prop-types": "off"
    }
  • 增加settings节点:
"settings": {
        "import/resolver": {
            "typescript": {}
        }
    }
  • extends节点中增加:
"extends": [
        "plugin:react/recommended",
        "airbnb",
        "plugin:@typescript-eslint/recommended"
    ]
  • plugins 节点中增加:
"plugins": ["react", "@typescript-eslint", "react-hooks"]
  • 在项目根目录增加.eslintignore文件,内容如下:
*.css
*.svg

到此,通过这些配置,可以通过Typescript项目提高ReactJS中的代码质量。

第六步、VSCode中安装ESLint插件保存时进行代码自动修复
  • 安装VS Code ESLint extension
    ESLint插件
  • 在项目根目录下创建.vscode目录
  • .vscode目录内创建文件settings.json,内容如下:
{
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
    "editor.formatOnSave": true,
    "eslint.alwaysShowStatus": true,
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    }
}

接着,重启一下VSCode使之生效,打开src/App.tsx文件,我们可以看到VSCode右下角ESLint已生效了,如出现未生效的图标,点击它,在弹出窗口上选择Allow.
ESLint

好了,这部分就完成了。

2、安装配置 Prettier

第一步、安装Prettier package

打开终端,在项目根目录执行如下安装命令:

yarn add prettier -D

或者

npm install --save-dev prettier
第二步、配置.prettierrc.json

在项目根目录下新建.prettierrc.json文件,内容如下:

{
    "trailingComma": "es5",
    "tabWidth": 4,
    "semi": false,
    "singleQuote": true
}
第三步、配置prettierignore

在项目根目录新建.prettierignore文件,内容如下:

node_modules
# Ignore artifacts:
build
coverage
第四步,执行Prettier命令
npx prettier --write src/App.tsx

可以看到它已经可以格式化代码了。
接着,在package.json文件中的scripts节点中增加:

"format": "prettier --write \"**/*.{ts,tsx,js,json,css,scss}\""

这样,就可以执行如下命令,对整个项目进行代码格式化

yarn format

或者

npm run format
第五步、VSCode中安装Prettier插件
  • 安装Prettier VSCode extension
    VSCode Prettier插件
  • 修改.vscode目录中的settings.json文件,如下:
{
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
    "editor.formatOnSave": true,
    "eslint.alwaysShowStatus": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
    "[json]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode",
      "editor.formatOnSave": true
    }
}

完成。

3、检查安装过的文件

package.json

devDependencies节点中应该包含:

"devDependencies": {
        "@typescript-eslint/eslint-plugin": "^4.26.1",
        "@typescript-eslint/parser": "^4.26.1",
        "eslint": "^7.28.0",
        "eslint-config-airbnb": "^18.2.1",
        "eslint-import-resolver-typescript": "^2.4.0",
        "eslint-plugin-import": "^2.23.4",
        "eslint-plugin-jsx-a11y": "^6.4.1",
        "eslint-plugin-react": "^7.24.0",
        "eslint-plugin-react-hooks": "^4.2.0",
        "prettier": "^2.3.1"
}

(版本不一致没事)

.prettierrc.json
{
    "trailingComma": "es5",
    "tabWidth": 4,
    "semi": false,
    "singleQuote": true
}

(可以修改成你喜欢的规则)

.eslintrc.json
{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "plugin:react/recommended",
        "airbnb",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": ["react", "@typescript-eslint", "react-hooks"],
    "rules": {
        "no-use-before-define": "off",
        "@typescript-eslint/no-use-before-define": ["error"],
        "react/jsx-filename-extension": ["warn", { "extensions": [".tsx"] }],
        "import/extensions": [
            "error",
            "ignorePackages",
            {
                "ts": "never",
                "tsx": "never"
            }
        ],
        "no-shadow": "off",
        "@typescript-eslint/no-shadow": ["error"],
        "max-len": ["warn", { "code": 80 }],
        "react-hooks/rules-of-hooks": "error",
        "react-hooks/exhaustive-deps": "warn",
        "import/prefer-default-export": "off",
        "react/prop-types": "off"
    },
    "settings": {
        "import/resolver": {
            "typescript": {}
        }
    }
}

(可以修改成你喜欢的规则)

.eslintignore
*.css
*.svg
.prettierignore
node_modules
# Ignore artifacts:
build
coverage

确保,没有遗漏以上某个配置文件。

4、解决ESLint和Prettier的冲突

在设置了Prettier和ESLint之后,您将看到,如果同时执行这两个命令,它们将开始在格式化规则方面有冲突。
在终端输入以下两个命令,可以看到这两个格式化完的App.tsx不一样:

npx eslint src/App.tsx --quiet --fix
npx prettier --write src/App.tsx

为了解决这个问题,我们可以将ESLint设置为仅对格式化规则使用Prettier,并避免这些相互冲突的规则。所以,让我们这样做!

第一步、禁用 ESLint 格式化规则
  • 安装eslint-config-prettier
yarn add  eslint-config-prettier -D

或者

npm install --save-dev eslint-config-prettier
  • .eslintrc.json文件中配置eslint-config-prettier
    extends节点最后增加prettier
"extends": [
        "plugin:react/recommended",
        "airbnb",
        "plugin:@typescript-eslint/recommended",
        "prettier"
]

再次运行这两个命令

npx eslint src/App.tsx --quiet --fix
npx prettier --write src/App.tsx

结果是不是一致了。

第二步、让 ESLint 使用 Prettier 的规则
  • 安装 eslint-plugin-prettier
yarn add eslint-plugin-prettier -D

或者

npm install --save-dev eslint-plugin-prettier
  • .eslintrc.json文件中配置eslint-plugin-prettier
    extends节点中增加plugin:prettier/recommended
"extends": [
        "plugin:react/recommended",
        "airbnb",
        "plugin:@typescript-eslint/recommended",
        "prettier",
        "plugin:prettier/recommended"
    ]

运行如下命令:

npx eslint src/App.tsx --quiet --fix

好了,完成。

5、安装配置commitlint

commitlint Github

第一步、安装commitlint

在终端,项目根目录下运行:

yarn add @commitlint/{config-conventional,cli} -D
或者
npm install --save-dev @commitlint/{config-conventional,cli}

windows下用这个:

npm install --save-dev @commitlint/config-conventional @commitlint/cli
第二步、配置commitlint

执行如下命令:

echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js

这里会在项目根目录下生成commitlint.config.js文件

第三步、安装和配置husky
# 安装 Husky v6
npm install husky --save-dev
# 或者
yarn add husky --dev

# 激活 hooks
npx husky install
# 或者
yarn husky install

# 添加 hook
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

好了,这样我们在提交代码时,随便输入的提交信息,将会提示错误,必须用规范的格式提交才能成功。
比如:在提交时这样写才行:

feat: 项目初始化

常用的提交规范:

# 主要type
feat:     增加新功能
fix:      修复bug

# 特殊type
docs:     只改动了文档相关的内容
style:    不影响代码含义的改动,例如去掉空格、改变缩进、增删分号
build:    构造工具的或者外部依赖的改动,例如webpack,npm
refactor: 代码重构时使用
revert:   执行git revert打印的message

# 暂不使用type
test:     添加测试或者修改现有测试
perf:     提高性能的改动
ci:       与CI(持续集成服务)有关的改动
chore:    不修改src或者test的其余修改,例如构建过程或辅助工具的变动

详情可参看官方文档

总结

工欲善其事必先利其器,这里把我们的开发环境打造好了,后面,会基于这个工程使用React17+Hook+TypeScript4 来完成一个完整的企业级权限管理系统。

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值