如何自动删除未使用的导入 - Visual Studio Code

Pro*_*000 8 visual-studio-code

我正在使用 Visual Studio Code 在 Unity 中创建游戏,因此我使用 C# 进行编程。我想知道如何:

A)在保存时强制编辑器删除未使用的导入。B) 删除项目范围内所有未使用的导入

当我用谷歌搜索时,我看到了对这个片段的暗示:

"editor.codeActionsOnSave": {
    "source.fixAll": true,
    "source.organizeImports": true
}
Run Code Online (Sandbox Code Playgroud)

没有人为我做任何事。

kri*_*yaa 14

这对我有用!


mic*_*ize 5

自 2022 年 8 月起, pylance 已原生支持这一功能,但需要source.unusedImports在列表中显式启用fixAll

在昨天的预发布之前(在撰写本文时)它存在一些性能问题,因此我建议安装版本2023.5.21或更高版本(如果有)。

这些是我当前正在使用的设置:

  "python.languageServer": "Pylance",
  "python.analysis.fixAll": [
    "source.unusedImports"
  ],
  "editor.codeActionsOnSave": {
    "source.organizeImports": true,
    "source.fixAll": true
  },
Run Code Online (Sandbox Code Playgroud)

在此之前,我使用任务autoflake以及“保存时触发任务”扩展。它和类似的任务会导致一些“文件内容较新”的抱怨,但大部分都可以:

// in task.json#tasks
{
  "type": "process",
  "label": "autoflake.removeUnusedImports",
  "command": "${command:python.interpreterPath}",
  "args": [
    "-m",
    "autoflake",
    "-i",
    "--remove-all-unused-imports",
    "${file}"
  ],
  "presentation": {
    "echo": true,
    "reveal": "silent",
    "focus": false,
    "panel": "shared",
    "showReuseMessage": false,
    "clear": false,
    "close": false
  },
  "problemMatcher": []
},
Run Code Online (Sandbox Code Playgroud)