如何在VSCode中访问片段扩展的用户设置

时间:2019-03-13 07:07:49

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

我正在尝试提供使用其首选引用样式的用户定义设置(配置)来自定义VS代码扩展的选项。我已经在package.json中配置了它:

"contributes": {
  "configuration": {
    "type": "object",
    "title": "Jasmine code snippets configuration",
    "properties": {
      "jasmineSnippets.quoteStyle": {
        "type": "string",
        "enum": [
          "'",
          "\"",
          "`"
        ],
        "default": "'",
        "description": "Code snippets quote style"
      }
    }
  }
},

并且可以像这样在我的settings.json中访问它:

"jasmineSnippets.quoteStyle": "`"

现在如何在snippets.json文件中使用该值?例如,对于此代码段,我想将硬编码的`更改为配置的属性。

"it": {
  "prefix": "it",
  "body": "it(`${1:should behave...}`, () => {\n\t$2\n});",
  "description": "creates a test method",
  "scope": "source.js"
},

我从the docs中可以找到的所有内容都无济于事,因为它假设您是从JavaScript文件而不是JSON文件读取的:

  

您可以使用vscode.workspace.getConfiguration('myExtension')从扩展程序中读取这些值。

1 个答案:

答案 0 :(得分:0)

我认为这需要实现CompletionItemProvider并从中返回代码段,而不是在JSON中静态声明它。这是一个可能看起来像的例子:

'use strict';
import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    vscode.languages.registerCompletionItemProvider('javascript', {
        provideCompletionItems(doc, pos, token, context) {
            var quote = vscode.workspace.getConfiguration('jasmineSnippets').get("quoteStyle", "`");
            return [
                {
                    label: "it",
                    insertText: new vscode.SnippetString(
                        `it(${quote}\${1:should behave...}${quote}, () => {\n\t$2\n});`),
                    detail: "creates a test method",
                    kind: vscode.CompletionItemKind.Snippet,
                },
            ];
        }
    });
}

然后在设置中使用"jasmineSnippets.quoteStyle": "\""