集成 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 插件,但如果现有插件不能满足你的特定要求,你可能需要创建自定义集成。

    ¥Code editors and IDEs: Integrating ESLint with code editors and IDEs can provide real-time feedback on code quality and automatically highlight potential issues as you type. Many editors already have ESLint plugins available, but you may need to create a custom integration if the existing plugins do not meet your specific requirements.

  • 自定义 linter 工具:如果你正在构建一个组合多个 linter 或添加特定功能的自定义 linter 工具,你可能希望将 ESLint 集成到你的工具中以提供 JavaScript linting 功能。

    ¥Custom linter tools: If you’re building a custom linter tool that combines multiple linters or adds specific functionality, you may want to integrate ESLint into your tool to provide JavaScript linting capabilities.

  • 代码审查工具:将 ESLint 与代码审查工具集成可以帮助自动化识别代码库中潜在问题的过程。

    ¥Code review tools: Integrating ESLint with code review tools can help automate the process of identifying potential issues in the codebase.

  • 学习平台:如果你正在开发学习平台或编码教程,集成 ESLint 可以在用户学习 JavaScript 时向他们提供实时反馈,帮助他们提高编码技能并学习最佳实践。

    ¥Learning platforms: If you are developing a learning platform or coding tutorial, integrating ESLint can provide real-time feedback to users as they learn JavaScript, helping them improve their coding skills and learn best practices.

  • 开发者工具集成:如果你正在创建或扩展开发者工具,例如打包器或测试框架,你可能希望集成 ESLint 以提供 linting 功能。你可以将 ESLint 直接集成到工具中或作为插件。

    ¥Developer tool integration: If you’re creating or extending a developer tool, such as a bundler or testing framework, you may want to integrate ESLint to provide linting capabilities. You can integrate ESLint directly into the tool or as a plugin.

你将构建什么

¥What You’ll Build

在本指南中,你将创建一个简单的 Node.js 项目,该项目使用 ESLint 类来检查文件并检索结果。

¥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(^18.18.0^20.9.0>=21.1.0

    ¥Node.js (^18.18.0, ^20.9.0, or >=21.1.0)

  • npm

  • 文本编辑器

    ¥A text editor

步骤 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 init -y

eslint 包安装为依赖(而不是开发依赖):

¥Install the eslint package as a dependency (not as a dev dependency):

npm install 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 参数可以是一个字符串或一个字符串数组,表示你要检查的文件路径。文件路径可以是 glob 或文件名。

¥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() 的调用中获取 linting 结果,然后将固定代码写回源文件。

¥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

定义一个函数以将 linting 结果输出到控制台。这应该特定于你的集成需求。例如,你可以将 linting 结果报告给用户界面。

¥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 类检查项目文件和检索结果的基本知识。这些知识可用于创建自定义集成,例如代码编辑器插件,以提供有关代码质量的实时反馈。

¥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 here.