跳至主要内容

代码风格检查

⚠️请注意,TSLint 现已进入维护阶段,您应该尝试使用 ESLint 替代。如果您对 TSLint 提示感兴趣,请查看来自 @azdanov 的此 PR。本节其余部分仅关注 ESLint。 您可以使用此工具将 TSlint 转换为 ESlint

⚠️这是一个不断发展的话题。typescript-eslint-parser 现已停止维护,并且ESLint 社区最近开始在 typescript-eslint 上开展工作,以使 ESLint 达到与 TSLint 完全相同的水平并实现互操作性。

请遵循 TypeScript + ESLint 文档,网址为 https://github.com/typescript-eslint/typescript-eslint

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

在您的 package.json 中添加一个 lint 脚本

  "scripts": {
"lint": "eslint 'src/**/*.ts'"
},

以及一个合适的 .eslintrc.js(此处使用 .js 而不是 .json,以便我们可以添加注释)

module.exports = {
env: {
es6: true,
node: true,
jest: true,
},
extends: "eslint:recommended",
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint"],
parserOptions: {
ecmaVersion: 2017,
sourceType: "module",
},
rules: {
indent: ["error", 2],
"linebreak-style": ["error", "unix"],
quotes: ["error", "single"],
"no-console": "warn",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{ vars: "all", args: "after-used", ignoreRestSiblings: false },
],
"@typescript-eslint/explicit-function-return-type": "warn", // Consider using explicit annotations for object literals and function return types even when they can be inferred.
"no-empty": "warn",
},
};

大部分内容来自 tsdx PR,该 PR 用于 **库**。

更多 .eslintrc.json 选项可供考虑,以及您可能希望用于 **应用程序** 的更多选项

{
"extends": [
"airbnb",
"prettier",
"prettier/react",
"plugin:prettier/recommended",
"plugin:jest/recommended",
"plugin:unicorn/recommended"
],
"plugins": ["prettier", "jest", "unicorn"],
"parserOptions": {
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"jest": true
},
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"]
}
}
},
"overrides": [
{
"files": ["**/*.ts", "**/*.tsx"],
"parser": "typescript-eslint-parser",
"rules": {
"no-undef": "off"
}
}
]
}

另一个很棒的资源是 @robertcoopercode 的“在 TypeScript 项目中使用 ESLint 和 Prettier”

Wes Bos 也正在开发 其 eslint+prettier 配置的 TypeScript 支持。

如果您正在寻找有关 Prettier 的信息,请查看 Prettier 指南。