您可以对 sn-ps 执行此操作。在您的 keybindings.json 中:
{
"key": "shift+alt+2",
"command": "editor.action.insertSnippet",
"when": "resourceFilename =~ /\\.spec\\.[tj]s$/",
// with the snippet text directly in the keybinding
"args": {
"snippet": "console.log($1)$0"
}
},
或者这个键绑定:
{
"key": "shift+alt+2",
"command": "editor.action.insertSnippet",
"when": "resourceFilename =~ /\\.spec\\.[tj]s$/",
"args": {
"name": "unit tests"
}
}
在一个 sn-p 文件中使用这个 sn-p:
"unit tests": {
// "prefix": "", // not used here
"body": [
"console.log($1)$0",
],
限制sn-p范围的关键是这个when子句:
"when": "resourceFilename =~ /\\.spec\\.[tj]s$/",
作为正则表达式,它将查找以 .spec.ts 或 .spec.js 结尾的文件名(请注意,您需要在句点之前进行两次转义)。所以使用resourceFileName 并构造一个正则表达式来查看它的末尾。
现在您选择的键绑定只能在 *.spec.ts 或 *.spec.js 文件中使用。
见a when clause acting as a regular expression, in keybindings documentation:
key-value when 子句操作符
when 子句有一个键值对运算符。表达方式
key =~ value 将右侧视为正则表达式
与左侧比赛。例如,贡献上下文
所有 Docker 文件的菜单项,可以使用:
"when": "resourceFilename =~ /docker/"
感谢这个问题,我找到了这个:resourceExtname with two dots not working