通过扩展更新 VS Code 用户设置

max*_*son 3 visual-studio-code vscode-extensions

我正在尝试创建一个简单的扩展来切换 VS Code 中测试文件的可见性。这是我目前的方法:

const testGlobs = [
  '**/__tests__',
  '**/__mocks__',
  '**/*.spec.js',
]

function hideTests() {
  const exclude = workspace.getConfiguration('files.exclude', vscode.ConfigurationTarget.Global)
  testGlobs.forEach(glob => exclude.update(glob, true, vscode.ConfigurationTarget.Global));
  console.log(exclude) // does not reflect the updated values
}
Run Code Online (Sandbox Code Playgroud)

这似乎没有影响。文件模式的设置保留false在我的用户设置文件中,就像注销exclude代码片段末尾的值时一样。

如何通过扩展代码正确更新设置?

max*_*son 6

解决了。我发布的代码实际上抛出了一个错误,但该update方法是异步的,因此错误被吞没了。通过在函数上使用 async/await,我能够看到错误,类似于:

'files.exclude.**/__tests__' is not a registered configuration.

基本上,我必须更新exclude整个配置,而不是更新其下的单个键,因为这些键只是配置值的一部分 - 它们本身并不是实际的配置键。工作解决方案:

async function hideTests() {
  const files = workspace.getConfiguration('files', ConfigurationTarget.Global)
  const exclude = files.get('exclude')
  testGlobs.forEach(g => exclude[g] = true)
  await files.update('exclude', exclude, ConfigurationTarget.Global)
}
Run Code Online (Sandbox Code Playgroud)