集成 Node.js API 教程
本指南将引导你整合 ESLint 类以对文件进行 lint 检查并获取结果,这对于创建与其他项目的集成非常有用。
🌐 This guide walks you through integrating the ESLint class to lint files and
retrieve results, which can be useful for creating integrations with other
projects.
为什么要创建集成?
🌐 Why Create an Integration?
如果你正在创建开发者工具,例如以下内容,你可能想要创建一个 ESLint 集成:
🌐 You might want to create an ESLint integration if you’re creating developer tooling, such as the following:
- 代码编辑器和集成开发环境(IDE):将 ESLint 与代码编辑器和 IDE 集成可以在编写代码时提供实时的代码质量反馈,并自动高亮潜在问题。许多编辑器已经提供了 ESLint 插件,但如果现有插件不能满足你的特定需求,你可能需要创建自定义集成。
- 自定义 linter 工具:如果你正在构建一个结合多个 linter 或添加特定功能的自定义 linter 工具,你可能希望将 ESLint 集成到你的工具中,以提供 JavaScript 代码检测功能。
- 代码审查工具:将 ESLint 与代码审查工具集成可以帮助自动化识别代码库中潜在问题的过程。
- 学习平台:如果你正在开发学习平台或编程教程,集成 ESLint 可以在用户学习 JavaScript 时提供实时反馈,帮助他们提高编码技能并学习最佳实践。
- 开发者工具集成:如果你正在创建或扩展开发者工具,例如打包工具或测试框架,你可能希望集成 ESLint 以提供代码检查功能。你可以将 ESLint 直接集成到工具中,或者作为插件集成。
你将构建什么
🌐 What You’ll Build
在本指南中,你将创建一个使用 ESLint 类来检查文件并获取结果的简单 Node.js 项目。
🌐 In this guide, you’ll create a simple Node.js project that uses the ESLint
class to lint files and retrieve results.
要求
🌐 Requirements
本教程假定你熟悉 JavaScript 和 Node.js。
🌐 This tutorial assumes you are familiar with JavaScript and Node.js.
要学习本教程,你需要具备以下条件:
🌐 To follow this tutorial, you’ll need to have the following:
- Node.js(
^20.19.0、^22.13.0或>=24) - npm
- 文本编辑器
步骤 1:设置
🌐 Step 1: Setup
首先,创建一个新的项目目录:
🌐 First, create a new project directory:
mkdir eslint-integration
cd eslint-integration
使用 package.json 文件初始化项目:
🌐 Initialize the project with a package.json file:
npm
npm init -y
yarn
yarn init -y
pnpm
pnpm init -y
bun
bun init -y
将 eslint 包安装为依赖(不是作为开发依赖):
🌐 Install the eslint package as a dependency (not as a dev dependency):
npm
npm install eslint
yarn
yarn add eslint
pnpm
pnpm add eslint
bun
bun add eslint
在项目根目录下创建一个名为 example-eslint-integration.js 的新文件:
🌐 Create a new file called example-eslint-integration.js in the project root:
touch example-eslint-integration.js
第2步:导入并配置 ESLint 实例
🌐 Step 2: Import and Configure the ESLint Instance
从 eslint 包中导入 ESLint 类并创建一个新实例。
🌐 Import the ESLint class from the eslint package and create a new instance.
你可以通过向 ESLint 构造函数传递一个选项对象来自定义 ESLint 配置:
🌐 You can customize the ESLint configuration by passing an options object to the
ESLint constructor:
// example-eslint-integration.js
const { ESLint } = require("eslint");
// Create an instance of ESLint with the configuration passed to the function
function createESLintInstance(overrideConfig) {
return new ESLint({
overrideConfigFile: true,
overrideConfig,
fix: true,
});
}
步骤 3:检查并修复文件
🌐 Step 3: Lint and Fix Files
要对文件进行 lint 检查,请使用 ESLint 实例的 lintFiles 方法。传递给 ESLint#lintFiles() 的 filePaths 参数可以是一个字符串或字符串数组,表示要进行 lint 检查的文件路径。文件路径可以是通配符模式或文件名。
🌐 To lint a file, use the lintFiles method of the ESLint instance. The
filePaths argument passed to ESLint#lintFiles() can be a string or an array
of strings, representing the file path(s) you want to lint. The file paths can
be globs or filenames.
静态方法 ESLint.outputFixes() 会获取来自对 ESLint#lintFiles() 调用的 lint 检查结果,然后将修复后的代码写回源文件。
🌐 The static method ESLint.outputFixes() takes the linting results from the call
to ESLint#lintFiles(), and then writes the fixed code back to the source
files.
// example-eslint-integration.js
// ... previous step's code to instantiate the ESLint instance
// Lint the specified files and return the results
async function lintAndFix(eslint, filePaths) {
const results = await eslint.lintFiles(filePaths);
// Apply automatic fixes and output fixed code
await ESLint.outputFixes(results);
return results;
}
步骤4:输出结果
🌐 Step 4: Output Results
定义一个函数,将代码检查结果输出到控制台。这应该针对你的集成需求。例如,你可以将代码检查结果报告给用户界面。
🌐 Define a function to output the linting results to the console. This should be specific to your integration’s needs. For example, you could report the linting results to a user interface.
在此示例中,我们将简单地将结果记录到控制台:
🌐 In this example, we’ll simply log the results to the console:
// example-eslint-integration.js
// ... previous step's code to instantiate the ESLint instance
// and get linting results.
// Log results to console if there are any problems
function outputLintingResults(results) {
// Identify the number of problems found
const problems = results.reduce(
(acc, result) => acc + result.errorCount + result.warningCount,
0,
);
if (problems > 0) {
console.log("Linting errors found!");
console.log(results);
} else {
console.log("No linting errors found.");
}
return results;
}
第5步:将所有部分组合在一起
🌐 Step 5: Put It All Together
将上述函数组合到一个名为 lintFiles 的新函数中。这个函数将作为你的集成的主要入口点:
🌐 Put the above functions together in a new function called lintFiles. This
function will be the main entry point for your integration:
// example-eslint-integration.js
// Put previous functions all together
async function lintFiles(filePaths) {
// The ESLint configuration. Alternatively, you could load the configuration
// from a .eslintrc file or just use the default config.
const overrideConfig = {
languageOptions: {
ecmaVersion: 2018,
sourceType: "commonjs",
},
rules: {
"no-console": "error",
"no-unused-vars": "warn",
},
};
const eslint = createESLintInstance(overrideConfig);
const results = await lintAndFix(eslint, filePaths);
return outputLintingResults(results);
}
// Export integration
module.exports = { lintFiles };
这是 example-eslint-integration.js 的完整代码示例:
🌐 Here’s the complete code example for example-eslint-integration.js:
const { ESLint } = require("eslint");
// Create an instance of ESLint with the configuration passed to the function
function createESLintInstance(overrideConfig) {
return new ESLint({
overrideConfigFile: true,
overrideConfig,
fix: true,
});
}
// Lint the specified files and return the results
async function lintAndFix(eslint, filePaths) {
const results = await eslint.lintFiles(filePaths);
// Apply automatic fixes and output fixed code
await ESLint.outputFixes(results);
return results;
}
// Log results to console if there are any problems
function outputLintingResults(results) {
// Identify the number of problems found
const problems = results.reduce(
(acc, result) => acc + result.errorCount + result.warningCount,
0,
);
if (problems > 0) {
console.log("Linting errors found!");
console.log(results);
} else {
console.log("No linting errors found.");
}
return results;
}
// Put previous functions all together
async function lintFiles(filePaths) {
// The ESLint configuration. Alternatively, you could load the configuration
// from an eslint.config.js file or just use the default config.
const overrideConfig = {
languageOptions: {
ecmaVersion: 2018,
sourceType: "commonjs",
},
rules: {
"no-console": "error",
"no-unused-vars": "warn",
},
};
const eslint = createESLintInstance(overrideConfig);
const results = await lintAndFix(eslint, filePaths);
return outputLintingResults(results);
}
// Export integration
module.exports = { lintFiles };
结论
🌐 Conclusion
在本教程中,我们已经介绍了使用 ESLint 类对文件进行 lint 检查并在项目中获取结果的基本知识。这些知识可以应用于创建自定义集成,例如代码编辑器插件,以提供对代码质量的实时反馈。
🌐 In this tutorial, we have covered the essentials of using the ESLint class to
lint files and retrieve results in your projects. This knowledge can be applied
to create custom integrations, such as code editor plugins, to provide real-time
feedback on code quality.
查看教程代码
🌐 View the Tutorial Code
你可以查看教程的带注释源代码。
🌐 You can view the annotated source code for the tutorial.