【问题标题】:Filter a snippet by filename or extension, like *.spec.ts and *.spec.js?按文件名或扩展名过滤片段,例如 *.spec.ts 和 *.spec.js?
【发布时间】:2018-10-12 09:22:04
【问题描述】:

我想添加几个 sn-ps 在创建 javascript/typescript 单元测试时使用,但我没有找到任何方法将 sn-p 的全局范围设置为 *.spec.ts*.spec.js

这可能吗? In the documentation 他们说范围是基于 language identifier 的,但我只是看到了一种为每种语言添加其他扩展的方法。

【问题讨论】:

    标签: visual-studio-code vscode-settings vscode-snippets


    【解决方案1】:

    您可以对 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

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 2010-10-07
      • 2018-02-26
      • 1970-01-01
      • 2019-09-10
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多