首页 > 解决方案 > 用于复制代码段行的 VSCode 代码段语法

问题描述

假设我想为打字稿界面创建一个 VSCode 片段,如下所示:

interface MyInterface{ 
  prop1: string; 
  prop2: string;
  prop3: string
}

现在我可以创建以下代码段:

"myinterface": {
  "prefix": "myinterface",
  "body": [
    "interface MyInterface{ ",
    "  prop1: string; ",
    "  prop2: string;",
    "  prop3: string",
    "}"
  ],
  "description": "not smart interface creator"
}

但是如果我想在我的界面中有一个prop4, prop5,怎么办?prop6无论如何有条件地扩展代码段,以便通过点击Tab我会被提示将另一个 prop 字段添加到具有格式的界面 ${1:propX}: ${2:string};

另一个用例是写出一个数组:

const myArray = [val1, val2, val3]

标签: visual-studio-codecode-snippetsvscode-snippets

解决方案


我认为没有任何方法可以直接做你想做的事。但是您可以使用下面的方法 2 非常接近。

方法一

"PS3": {
  "prefix": "ps3",
  "body": [
    "interface MyInterface{",  
    "${1/([^,]+)([,\\s]*|)/\t$1: string;${2:+\n}/g}",
    "}"
  ]
},

这类似于我在具有可变数量参数的片段中使用的技术。这是上面的演示:

将多个道具添加到片段

但是您无法使用此方法选择和轻松编辑变量或类型。


方法二

这比较棘手,但会导致选择的键和类型更容易更改。你需要 2 个片段”

"myinterface": {
  "prefix": "myinterface",
  "body": [
    "interface MyInterface{ ",

    // I jazzed it up by adding a choice transform
    "\t${1:propX}: ${0:${2|string,int,bool|}};",
    "}"
  ],
  "description": "sorta smart interface creator"
},

"addProps": {
  "prefix": "[int, bool, string]",  // note multiple prefixes
  "body": [
    "$TM_SELECTED_TEXT;",
    "${1:propX}: ${0:${2|string,int,bool|}}",
  ],
  "description": "add props to interface"
},

基本上,这使用第一个片段的结尾作为附加key: type对的前缀。演示:

将选项添加到片段

选择标签后再次选择您选择的int/bool/string标签以移动到最后 - 这将自动选择您选择的内容int/bool/string

Ctrl现在您可以使用+触发第二个片段的建议Space 以插入一个键:一次键入对。请注意,第二个片段有三个前缀来匹配您的类型选择,在行尾重新插入您的选择并添加另一个键:type line below。


推荐阅读