我正在使用 Visual Studio Code 在 Unity 中创建游戏,因此我使用 C# 进行编程。 我想知道如何:
A)在保存时强制编辑器删除未使用的导入。 B) 删除项目范围内所有未使用的导入
当我用谷歌搜索时,我看到了对这个片段的暗示:
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": true
}
没有人为我做任何事情。
这对我有用!
按
ctrl+ shift+ P
搜索
settings.json
添加以下代码
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": true
},
您可以轻松完成此操作,只需按键盘上的
SHIFT
+ ALT
+ O
。
截至 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
},
在此之前我使用一个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": []
},
Ctrl+Alt+O
来优化导入。使用文件中的快捷方式仅对 1 个文件执行操作。要在目录和所有子目录级别执行此操作,请从项目资源管理器中选择文件夹,然后单击快捷方式。它将优化所有子目录中文件的导入。
注意:更新键绑定将更改 VSCode 的默认键绑定。检查 https://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard.pdf 了解有关 IntelliJ 键绑定的详细信息。
如果您熟悉 Visual Studio 键绑定,则可以使用它。