Skip to main content

代码规范

记录 npm 项目代码规范相关配置,基于 eslint 和 typescript

# 安装依赖
npm install eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev

# 配置 eslint
npx eslint --init
# 根据提示选择

手动检测


# 检测并修复
npx eslint src/**/*.{js,jsx,ts,tsx} --fix

# 检查 ts 编译错误
npx tsc --noEmit --skipLibCheck --incremental --tsBuildInfoFile tsconfig.tsbuildinfo

eslint 命令行详细用法

ts 的编译选项也可以在 tsconfig.json 中事先配置:

{
"compilerOptions": {
"noEmit": true, // 不生成输出文件
"skipLibCheck": true, // 跳过库文件检查
"incremental": true, // 增量编译
"tsBuildInfoFile": "tsconfig.tsbuildinfo" // 生成编译信息文件
}
}

配置之后只需执行 npx tsc 即可

配置成 npm scripts

在 package.json 中添加 scripts

{
"scripts": {
"lint": "eslint src/**/*.{js,jsx,ts,tsx} --fix",
"tsc": "tsc --noEmit --skipLibCheck --incremental --tsBuildInfoFile tsconfig.tsbuildinfo"
}
}

之后只需执行 npm run lintnpm run tsc 即可

使用 husky 在 git commit 前自动检测代码

husky 可以保证未通过检测的代码无法提交到 git 仓库

注意:先确保 npm 项目的根目录(package.json 所在目录)和 git 仓库的根目录(.git 所在目录)一致,不然可能无法正常使用 husky

# 安装 husky
npm install husky --save-dev

# 初始化 husky , 会生成 .husky 目录,并生成 pre-commit 文件
npx husky init

# 之后可以在 pre-commit 文件中添加检测命令,以上面配置好的 npm scripts 为例:npm run lint && npm run tsc

使用 lint-staged

可以做到只对修改的文件进行 lint 检测

注意 ts 编译错误无法只检测修改的文件,因为代码文件之间会有依赖关系,上面是通过增量编译 --incremental 来提高效率的

# 安装 lint-staged
npm install lint-staged --save-dev

在 package.json 中添加 lint-staged 配置:

{
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx}": [
"eslint --fix"
]
}
}

修改 pre-commit 文件:

npx lint-staged && npm run tsc