likes
comments
collection
share

eslint之针对ts里面未使用的变量进行校验

作者站长头像
站长
· 阅读数 62

一、问题概述

项目配置了eslint的规则,即对未使用的变量进行报错显示,但是在ts的声明文件里面,会有一些函数的声明,函数里面会有参数的定义,这个时候提交代码的时候,eslint 也会报错说不允许有未使用的变量,但其实这个时候不应该报错。 例如下图: eslint之针对ts里面未使用的变量进行校验

当提交的时候,setVisible里面的val就会报错,那我们要做的就是去掉 ts里面这个声明文件未使用变量的校验。

二、解决方法

  1. 在 eslint的配置文件的 extends 字段里面加上 "plugin:@typescript-eslint/eslint-recommended"和"plugin:@typescript-eslint/recommended"
  2. 在 eslint的配置文件的 plugins 字段里面加上 @typescript-eslint
  3. 最后需要手动安装@typescript-eslint/eslint-plugin包

(备注:因为我们的eslint 是提取出来一个包的,所以我把@typescript-eslint/eslint-plugin这个包安装在了dependencies,具体可以根据自己项目情况选择安装到dependencies还是devDependencies,安装命令是npm install @typescript-eslint/eslint-plugin@latest --save)

eslint之针对ts里面未使用的变量进行校验 eslint之针对ts里面未使用的变量进行校验

三、eslint配置完整代码

module.exports = {
  env: {
    node: true,
    browser: true,
    es2021: true,
  },
  parser: "@typescript-eslint/parser",
  extends: [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
  ],
  parserOptions: {
    babelOptions: {
      ecmaVersion: "es2020",
      ecmaFeatures: {
        globalReturn: true,
        jsx: true,
      },
      lib: ["ES2020"],
    },
  },
  plugins: ["react", "@typescript-eslint"],
  settings: {
    react: {
      version: "detect",
    },
  },
  overrides: [
    {
      files: ["*.ts", "*.tsx"],
      rules: {
        "no-undef": "off",
        "react/prop-types": "off",
      },
    },
  ],
};

四、提交测试

经过以上配置,最后提交没有报错。

eslint之针对ts里面未使用的变量进行校验

转载自:https://juejin.cn/post/7224325360597909565
评论
请登录