通过扩展更新VS代码用户设置代码、用户、VS

2023-09-03 10:58:44 作者:初顾

我正在尝试创建一个简单的扩展来切换VS代码中测试文件的可见性。以下是我目前的做法:

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
}

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

VScode安装 配置和使用

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

推荐答案

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

'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)
}
 
精彩推荐