如何使用命令删除未使用的导入?

How to remove unused imports with a command?

我的 nx 项目中有导入声明但没有任何用处的文件,我想删除它们。

在 Whosebug 中搜索后,我找到了在 vscode 中打开文件的答案,然后按 alt+shift+o,当声明未被使用时,它会删除并排序导入。

但我有 10,000 个文件。那么在所有这些文件中是否有执行此操作的命令?我正在查看 eslint,但没有相关规定。

如果您是 重度用户,那么您只需打开您的首选项设置,然后将以下内容添加到您的 settings.json:

    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
    }

或者您可以制作一个独立的 文件,其中包含以下内容:

{
    "extends": ["tslint-etc"],
    "rules": {
            "no-unsed-declaration: true"
}}

然后 运行 以下命令修复导入:

tslint --config tslint-imports.json --fix --project

然后使用

ng build

ng build name_of_project --configuration=production 

安装 no-unused-imports plugin

将未使用的导入添加到 .eslintrc 文件的插件部分

{
  "plugins": ["...", "unused-imports"]
}

添加以下规则

"no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
  "warn",
  { "vars": "all", "varsIgnorePattern": "^_", "args": "after-used", "argsIgnorePattern": "^_" }
    ],

然后将脚本添加到您的 package.json 文件

"scripts": {
   ...
   "fix-lint-errors": "eslint nx --fix"
},

从命令行 运行 脚本

npm run fix-lint-errors

yarn fix-lint-errors