ESLint 是一个用于识别和报告在 ECMAScript/JavaScript 代码中发现的错误的工具,其目标是使代码更加一致并避免错误。
自动配置eslint
pnpm create @eslint/config@latest
- 在
package.json中添加命令
"scripts": {
"eslint": "pnpm dlx eslint --fix"
}
忽略文件
在 eslint.config.js 文件中,使用 globalIgnores() 辅助函数来指定要忽略的文件模式。
// eslint.config.js
import { defineConfig, globalIgnores } from "eslint/config";
export default defineConfig([globalIgnores(["public/","dist/"])]);
配置插件
非范围包和范围包都可以省略 eslint-plugin- 前缀。
非范围包:
//eslint.config.js
{
// ...
"plugins": [
"jquery", // means eslint-plugin-jquery
]
// ...
}
范围包:
//eslint.config.js
{
// ...
"plugins": [
"@jquery/jquery", // means @jquery/eslint-plugin-jquery
"@foobar" // means @foobar/eslint-plugin
]
// ...
}
共享配置
要共享你的 ESLint 配置,请创建一个 可共享配置。 你可以在 npm 上发布你的可共享配置,以便其他人可以下载并在他们的 ESLint 项目中使用它。
创建可共享的配置
可共享配置只是导出配置对象的 npm 包。模块名称必须采用以下形式之一:
- 以
eslint-config-开头,例如eslint-config-myconfig。 - 成为 npm 作用域模块。,例如
@scope/eslint-config或@scope/eslint-config-myconfig。
使用可共享配置
配置文件的 extends 字段中包含模块名称。 例如:
{
"extends": "eslint-config-myconfig"
}
可以省略 eslint-config-,ESLint 会自动采用它:
{
"extends": "myconfig"
}
使用共享配置eslint-config-prettier
import { defineConfig} from "eslint/config";
import someConfig from "some-other-config-you-use";
//注意这里的“/flat”后缀,与默认条目的区别在于
//`/flat`在导出对象中添加了`name`属性以改进
import eslintConfigPrettier from "eslint-config-prettier/flat";
export default defineConfig([
someConfig,
eslintConfigPrettier,
]);
- 在
package.json中添加命令
"scripts": {
"eslint": "pnpm dlx eslint --fix",
}