Skip to main content

入门

快速入门

¥Quickstart

本页是 ESLint 的新 "flat" 配置格式 的快速入门指南,可帮助你从零开始尽快使用我们推荐的规则对 TypeScript 代码进行 linting。

¥This page is a quick-start for ESLint's new "flat" config format to go from zero to linting with our recommended rules on your TypeScript code as quickly as possible.

注意

步骤 1:安装

¥Step 1: Installation

首先,安装 ESLintTypeScript我们的工具 所需的软件包:

¥First, install the required packages for ESLint, TypeScript, and our tooling:

npm install --save-dev eslint @eslint/js typescript typescript-eslint

步骤 2:配置

¥Step 2: Configuration

接下来,在项目的根目录中创建一个 eslint.config.mjs 配置文件,并使用以下内容填充它:

¥Next, create an eslint.config.mjs config file in the root of your project, and populate it with the following:

eslint.config.mjs
// @ts-check

import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.recommended,
);

此代码将启用我们的 推荐配置 进行 linting。

¥This code will enable our recommended configuration for linting.

Aside on file extensions

.mjs 扩展使文件使用 ES 模块 (ESM) 格式。Node 默认以 CommonJS (CJS) 格式解释 .js 文件,但如果你的 package.json 中有 "type": "module",你也可以使用 eslint.config.js

¥The .mjs extension makes the file use the ES modules (ESM) format. Node interprets .js files in the CommonJS (CJS) format by default, but if you have "type": "module" in your package.json, you can also use eslint.config.js.

详情

¥Details

步骤 3:运行 ESLint

¥Step 3: Running ESLint

打开项目根目录的终端并运行以下命令:

¥Open a terminal to the root of your project and run the following command:

npx eslint .

ESLint 将检查当前文件夹中的所有 TypeScript 兼容文件,并将结果输出到你的终端。

¥ESLint will lint all TypeScript compatible files within the current folder, and will output the results to your terminal.

下一步

¥Next Steps

如果你在运行此功能时遇到问题,请查看我们的 故障排除和常见问题解答

¥If you're having problems getting this working, please have a look at our Troubleshooting & FAQs.

其他配置

¥Additional Configs

我们建议你考虑启用以下两个配置:

¥We recommend you consider enabling the following two configs:

  • strictrecommended 的超集,包含更多有态度的规则,这些规则也可能捕获错误。

    ¥strict: a superset of recommended that includes more opinionated rules which may also catch bugs.

  • stylistic:强制一致样式的附加规则,不会显著捕获错误或更改逻辑。

    ¥stylistic: additional rules that enforce consistent styling without significantly catching bugs or changing logic.

eslint.config.mjs
export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.recommended,
tseslint.configs.strict,
tseslint.configs.stylistic,
);

你可以在我们的 共享配置文档 中阅读有关这些内容的更多信息。

¥You can read more about these in our shared configurations docs.

类型化 Linting

¥Typed Linting

我们还提供大量强大的规则,利用 TypeScript 类型信息的强大功能。访问下一页获取类型化规则设置指南

¥We also provide a plethora of powerful rules that utilize the power of TypeScript's type information. Visit the next page for a typed rules setup guide.

文档资源

¥Documentation Resources