如何通过代码调用ESLint格式化文件?报错排查与疑问解答
ESLint Node.js API 使用问题解答
问题背景
你通过ESLint Node.js API编写了lint脚本,希望完全忽略项目中的.eslintrc.json,使用自定义的eslint.code.json配置,但运行时出现插件加载错误,且预期的代码修复未生效。
你的lint脚本
const { ESLint } = require('eslint') const ESLINT_CONFIG = require('../eslint.code.json') async function lint(path) { // 1. Create an instance. const eslint = new ESLint({ fix: true, overrideConfig: ESLINT_CONFIG, useEslintrc: false, }) // 2. Lint files. const results = await eslint.lintFiles([path]) // 3. Format the results. const formatter = await eslint.loadFormatter('stylish') const resultText = formatter.format(results) console.log(resultText) } lint('example.ts')
自定义配置 eslint.code.json
{ "env": { "browser": true, "es2021": true }, "parserOptions": { "ecmaVersion": "latest", "sourceType": "module", "project": ["./tsconfig.json"] }, "parser": "@typescript-eslint/parser", "plugins": [ "@typescript-eslint", "import", "simple-import-sort", "sort-exports", "typescript-sort-keys", "sort-keys", "prettier" ], "extends": ["prettier", "next"], "rules": { "curly": 2, "@typescript-eslint/quotes": [ "error", "single", { "avoidEscape": true, "allowTemplateLiterals": true } ], "padding-line-between-statements": "off", "@typescript-eslint/padding-line-between-statements": [ "error", { "blankLine": "always", "prev": "*", "next": "function" }, { "blankLine": "always", "prev": "*", "next": "block" }, { "blankLine": "always", "prev": "*", "next": "return" }, { "blankLine": "always", "prev": "*", "next": "type" } ] } }
tsconfig.json
{ "compilerOptions": { "target": "es5", "declaration": true, "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "esModuleInterop": true, "module": "commonjs", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react", "incremental": true, "outDir": "dist", "baseUrl": ".", "declarationMap": true }, "exclude": ["node_modules", "dist"] }
待处理示例文件 example.ts
function tanh(x) { return x.clamp(-15, 15).tanh() } function artanh(x: TorchTensor) { x = x.clamp(-1 + 1e-7, 1 - 1e-7) return torch .log(1 + x) .sub(torch.log(1 - x)) .mul(0.5) }
报错信息
node:internal/errors:491 ErrorCaptureStackTrace(err); ^ TypeError [ERR_INVALID_ARG_VALUE]: Failed to load plugin '@typescript-eslint' declared in 'CLIOptions': The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received '' at new NodeError (node:internal/errors:400:5) at createRequire (node:internal/modules/cjs/loader:1333:13) at Object.resolve (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2325:16) at ModuleResolver.resolve (/exampleproj/node_modules/@rushstack/eslint-patch/lib/modern-module-resolution.js:210:48) at ConfigArrayFactory._loadPlugin (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3392:33) at ConfigArrayFactory._loadPlugin (/exampleproj/node_modules/@rushstack/eslint-patch/lib/modern-module-resolution.js:219:43) at /exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3283:33 at Array.reduce (<anonymous>) at ConfigArrayFactory._loadPlugins (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3279:22) at ConfigArrayFactory._normalizeObjectConfigDataBody (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3079:44) { code: 'ERR_INVALID_ARG_VALUE' }
疑问与解答
1. 操作有误的地方
核心问题是ESLint实例初始化时未指定cwd参数:
- 当设置
useEslintrc: false时,ESLint无法自动识别项目根目录,导致解析插件、tsconfig.json等路径时出现空值错误。 - 另外,你传入的
path是相对路径,若脚本不在项目根目录执行,也会导致文件定位异常。
修改后的初始化代码:
const path = require('path'); // ... const eslint = new ESLint({ fix: true, overrideConfig: ESLINT_CONFIG, useEslintrc: false, // 指定项目根目录为当前脚本所在目录的上级(根据你的require路径../eslint.code.json调整) cwd: path.resolve(__dirname, '../'), })
同时,调用lint时建议使用绝对路径:
lint(path.resolve(__dirname, '../example.ts'))
2. 配置设置的问题
你的配置存在几个需要调整的点:
extends中的next:若使用的是eslint-config-next,需确保已安装该包;若不需要Next.js相关规则,可移除该项。parserOptions.project:建议依赖cwd参数来确保ESLint能找到tsconfig.json,指定cwd后"./tsconfig.json"可正常识别,更稳妥的方式是在配置中使用绝对路径(或通过脚本动态注入)。- 插件依赖检查:确保所有配置中列出的插件已安装,比如
@typescript-eslint/eslint-plugin、eslint-plugin-prettier、eslint-config-prettier等,缺少依赖会导致加载失败。 - 规则有效性:
@typescript-eslint/padding-line-between-statements的规则配置是正确的,修复路径问题后应该能正常触发函数间添加空行的修复。
3. stylish是什么
stylish是ESLint内置的格式化器,作用是把lint检查的结果(错误、警告、修复信息)转换成可读性强的命令行输出格式,和Prettier无关:
- Prettier是独立的代码格式化工具,主要负责代码风格(如缩进、换行、引号)的统一;ESLint的格式化器只是用来展示lint结果的输出样式。
- 除了
stylish,ESLint还内置了json、codeframe、unix等格式化器,你可以根据需求选择,比如用json做结果的自动化处理,用codeframe更清晰地定位代码问题。
内容的提问来源于stack exchange,提问作者Lance Pollard
相关产品推荐
相关产品推荐

