【问题标题】:How to tell my linter to flag require() statements with a warning如何告诉我的 linter 用警告标记 require() 语句
【发布时间】:2021-10-27 12:18:06
【问题描述】:

我已经使用 typescript 建立了一个新的 nodeJS 项目。我的 linter 用错误标记我,例如:

import authentication from "./routes/authentication"; // Flags "Cannot find module ..."

我希望它为这些语句标记警告/错误,因为当我尝试加载它时它们会破坏我的应用程序:

const pool = require("../database/db"); // Currently not flagging as a warning either for the fact that the file does not exist, or that it is using a require() statement.

我猜eslint 正在做我的 linting。但我没有明确设置它。我尝试创建和使用.eslint.rc 文件,但什么也没发生。

  1. 如何检查我的 linter 是什么?我在我的 VS-Code 设置中找不到任何东西来说明我在使用什么。我在我的 package.jsontsconfig.json 文件中也找不到任何引用它的引用 linter?
  2. 然后如何让我的 linter 标记 require() 语句?

所以看起来eslint 已经在运行了。它安装在我的扩展中,但我不知道它使用了什么规则。一定是一些默认值?

我运行yarn add eslint -Dnpx eslint --init 来设置eslint。然后我更改了.eslintrc.js 文件中的rules: 对象。这似乎改变了 linting,这表明我已经在使用 eslint

我还没有弄清楚如何标记require() 语句的错误。我找到了this YouTube video,这说明:

  • require() 语句只是函数。我们可以在if() 条件和函数中编写require() 语句。 import ... from ... 语句无法做到这一点
  • 因为require() 语句是函数,它们只在运行时被调用。 imports 是静态的,因此它们在解析时由打字稿检查。这很有用,因为这意味着我们可以在进入运行时之前遇到错误。

【问题讨论】:

  • 如果您使用的是 eslint 或 tslint,则有一个名为 no-require-imports see link 的规则。如果使用 eslint,你必须先安装 typescript-eslint 包。
  • 好的,所以如果我运行yarn add typescript-eslint -D 然后将'no-var-requires': 1, 添加到.eslint 下的.eslint 文件rules: {} 那么它应该可以工作吗?只是我刚试的时候没有任何效果?
  • @Karl-JohanSjögren 我已经修好了。我不想安装typescript-eslint。当我按照以下说明操作时,它起作用了:github.com/typescript-eslint/typescript-eslint/blob/master/docs/…。出于某种原因,在我运行以下命令之前,我的 linting 并没有拾取一些项目:yarn eslint . --ext .js,.jsx,.ts,.tsx

标签: node.js typescript express visual-studio-code eslint


【解决方案1】:
  1. 除了使用github.com/typescript-eslint/... 指令设置eslint 然后使用.eslintrc.js 文件以查看规则已更改之外,我从未找到更好的方法来检查我的VS-Code 正在运行的linter。即使这样,我也必须在.eslintrc.js 中的rules:{} 开始生效之前运行yarn eslint . --ext .js,.jsx,.ts,.tsx
  2. 为了让 require() 语句与我的 linter 一起标记,我将以下内容添加到我的 .eslintrc.js rules:{} 属性中:
  rules: {
    "@typescript-eslint/no-var-requires": 1,
    ...
  }

尽管这直到我按照第 1 项中描述的步骤之后才生效。如上所述,由于某种原因,我不得不在我的.eslintrc.js 中的rules:{} 开始使用之前运行yarn eslint . --ext .js,.jsx,.ts,.tsx效果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 2017-07-16
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    相关资源
    最近更新 更多