You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

VSCode配置同一快捷键,根据文件扩展名插入对应代码片段

解决方案

你只需要在VS Code的快捷键配置文件(keybindings.json)里添加两个针对性的配置项,让同一个快捷键根据当前文件类型触发不同的代码片段即可:

  1. 打开快捷键配置文件:按下Ctrl+Shift+P(Windows/Linux)或Cmd+Shift+P(Mac),输入**Preferences: Open Keyboard Shortcuts (JSON)**并回车。
  2. 替换或添加以下配置:
[
  {
    "key": "ctrl+shift+l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus && editorLangId == 'python'",
    "args": {
      "snippet": "print('$0',)"
    }
  },
  {
    "key": "ctrl+shift+l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus && (editorLangId == 'javascript' || editorLangId == 'typescript')",
    "args": {
      "snippet": "console.log('$0',)"
    }
  }
]

配置说明:

  • when条件:通过editorLangId判断当前文件类型,确保快捷键只在对应类型的文件中触发正确的片段:
    • editorLangId == 'python' 匹配所有.py文件,插入Python的print语句
    • editorLangId == 'javascript' || editorLangId == 'typescript' 匹配.js.ts文件,插入console.log
  • $0标记:这是代码片段的光标占位符,插入后光标会自动定位到这个位置,方便你直接输入要打印的内容

如果之后需要适配其他文件类型(比如.jsx.tsx),只需要在when条件里添加对应的editorLangId即可,例如:editorLangId == 'javascriptreact' || editorLangId == 'typescriptreact'

内容的提问来源于stack exchange,提问作者suku

火山引擎 最新活动