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

Node.js+Typescript项目如何配置linter对require()语句触发警告

1. 确认当前使用的linter的方法

  • 打开VS Code的「输出」面板,点击面板右上角的下拉菜单,选择ESLint选项,如果有运行时日志输出,说明当前生效的是VS Code的ESLint扩展;如果下拉菜单中有其他linter选项(如TSLint、JSHint等)且有对应日志,就是对应linter在生效。
  • 在项目根目录执行npx eslint .命令,对比命令行输出的报错信息和VS Code编辑器内的报错是否完全一致,如果一致说明ESLint使用的是项目本地配置,不一致则是VS Code扩展使用了全局默认规则。

2. 配置ESLint触发require语句提示的方法

你需要实现两个校验规则:禁止使用CommonJS的require()语法、校验导入的模块路径是否存在,分别按以下步骤配置:

2.1 禁用require()语法

首先确保你已经安装了TS项目ESLint的必备依赖:

yarn add @typescript-eslint/parser @typescript-eslint/eslint-plugin -D

在你的.eslintrc.js配置文件中加入以下规则:

module.exports = {
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
    // 禁止全局作用域下使用require导入
    '@typescript-eslint/no-var-requires': 'error',
    // 禁止所有场景下使用require导入(包括局部作用域)
    '@typescript-eslint/no-require-imports': 'error'
  }
}

2.2 校验导入的模块路径是否存在

安装路径校验所需的插件:

yarn add eslint-plugin-import eslint-import-resolver-typescript -D

在.eslintrc.js中追加以下配置:

module.exports = {
  // 原有配置保持不变
  plugins: ['@typescript-eslint', 'import'],
  settings: {
    'import/resolver': {
      typescript: {
        // 此处路径指向你项目中的tsconfig.json
        project: './tsconfig.json'
      }
    }
  },
  rules: {
    // 原有规则保持不变
    'import/no-unresolved': ['error', { commonjs: true, amd: true }]
  }
}

配置完成后,按下Ctrl+Shift+P(Mac系统为Cmd+Shift+P)调出命令面板,执行「ESLint: Restart ESLint Server」重启服务,配置即可生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:06:03