eslint: 移除不需要的 unused import

项目中移除不需要 import 代码
更新于: 2024-12-07 11:28:35

安装

yarn add -D eslint-plugin-unused-imports

配置

// eslint.config.js

import tseslint from "typescript-eslint";
import unusedImports from "eslint-plugin-unused-imports";

export default tseslint.config(
  {
    plugins: {
      "unused-imports": unusedImports,
    },
    rules: {
      "unused-imports/no-unused-imports": "warn",
    },
  }
);

我的配置

  • .eslintignore
  • .eslintrc.cjs
  • package.json

.eslintignore 不需要的文件忽略掉

node_modules/
dist/
prettier.config.cjs
.eslintrc.cjs
public/
assets/
vite-env.d.ts
.prettierignore
package-lock.json
package.json
postcss.config.cjs
tailwind.config.cjs
tsconfig.json
tsconfig.node.json
vite.config.ts

.eslintrc.cjs

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'plugin:prettier/recommended',
  ],
  overrides: [],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react', 'unused-imports'],
  rules: {
    '@typescript-eslint/no-unused-vars': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    'unused-imports/no-unused-imports': 'warn',
    'react/display-name': 'off',
    'react/react-in-jsx-scope': 'off',
    "react/prop-types": "off",
    "react/jsx-no-undef": "off",
    'prettier/prettier': [
      'warn',
      {
        endOfLine: 'auto',
      },
    ],
  },
  settings: {
    'import/parsers': {
      '@typescript-eslint/parser': ['.ts', '.tsx'],
    },
    react: {
      version: 'detect',
    },
    'import/resolver': {
      node: {
        paths: ['src'],
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
    },
  },
};

package.json,重点是 eslint 的包

{
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^7.9.0",
    "@typescript-eslint/parser": "^7.9.0",
    "eslint": "^8.57.0",
    "eslint-config-prettier": "^8.10.0",
    "eslint-config-standard-with-typescript": "^34.0.0",
    "eslint-plugin-import": "^2.29.1",
    "eslint-plugin-n": "^17.2.1",
    "eslint-plugin-prettier": "^5.1.3",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.2",
    "eslint-plugin-react-refresh": "^0.4.7",
    "eslint-plugin-unused-imports": "^3.1.0",
  }
}

测试执行

eslint ... --fix

执行结果