You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置typescript-eslint以支持Deno语法与特性?

配置 typescript-eslint 支持 Deno 语法的完整方案

问题背景

typescript-eslint 官方推荐与 Deno 搭配使用「双检模式」——先用各自工具完成专属检查,再通过 ESLint 执行类型检查,但未明确说明如何配置以支持 Deno 特有的语法特性。需要解决以下核心问题:

  • 识别导入语句中的 JSR(jsr:@std/expect)和 NPM(npm:@types/node)前缀
  • 全局识别 Deno 对象及其内置方法
  • 针对 deno.json 导入映射中声明的依赖,关闭「模块未在 package.json 依赖中列出」的误报警告

测试用例代码(需无报错通过检查):

import { assertEquals } from "@std/assert";

Deno.test(function addTest() {
  assertEquals(2 + 3, 5);
});

解决方案

1. 配置解析器与导入解析器,识别 JSR/NPM 前缀导入

使用适配 Deno v2 的 @redabacha/eslint-import-resolver-deno 作为导入解析器,让 ESLint 正确识别 Deno 风格的导入路径:

首先安装依赖(在 Deno 项目中用 npm 或 yarn 安装 ESLint 相关包):

npm install -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-import @redabacha/eslint-import-resolver-deno

在扁平配置文件 eslint.config.js 中添加以下配置:

import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginImport from "eslint-plugin-import";

export default [
  // 基础规则集
  pluginJs.configs.recommended,
  ...tseslint.configs.recommendedTypeChecked,
  pluginImport.configs.recommended,
  
  // Deno 专属配置
  {
    files: ["**/*.ts"],
    languageOptions: {
      parser: tseslint.parser,
      parserOptions: {
        project: "./tsconfig.json", // 指向 Deno 生成的 tsconfig 文件
        tsconfigRootDir: import.meta.dirname,
      },
      globals: {
        ...globals.deno, // 快速注入 Deno 全局变量
      },
    },
    settings: {
      "import/resolver": {
        "@redabacha/eslint-import-resolver-deno": {
          denoConfig: "./deno.json", // 指定 deno.json 配置文件路径
        },
      },
    },
  },
];

2. 让 TypeScript 识别 Deno 全局类型

确保你的 tsconfig.json 包含 Deno 的类型声明(可通过 deno init 命令自动生成):

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "types": ["deno.ns"] // 加载 Deno 命名空间的类型定义
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules"]
}

此配置会让 typescript-eslint 通过 TypeScript 类型系统自动识别 Deno 全局对象及其所有方法,无需额外手动声明 globals。

3. 关闭导入依赖的误报警告

针对 import/no-extraneous-dependencies 规则,添加允许的 Deno 依赖前缀,或直接禁用 package.json 依赖检查:

在 eslint.config.js 的规则配置块中添加:

{
  rules: {
    "import/no-extraneous-dependencies": [
      "error",
      {
        allowModules: [
          "@std/*", // 允许 Deno 标准库导入
          "jsr:@*", // 允许所有 JSR 生态包
          "npm:@*"  // 允许所有 NPM 前缀包
        ],
        packageDir: false // 禁用基于 package.json 的依赖检查
      }
    ]
  }
}

如果已配置 @redabacha/eslint-import-resolver-deno,它会自动读取 deno.json 中的导入映射,此时可简化规则为仅禁用 package.json 检查。

验证配置

将开头的测试代码保存为 main_test.ts,运行 ESLint 检查:

npx eslint main_test.ts

此时应无任何报错,说明配置生效。

内容的提问来源于stack exchange,提问作者Dan Dascalescu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:49:57