Updating VS Code user settings via an extension

2020-07-25 01:07发布

问题:

I'm trying to create a simple extension for toggling the visibility of test files in VS Code. Here's my current approach:

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
}

This appears to have no impact. The settings for the file patterns remain false in my user settings file, as they do when logging out the values of exclude at the end of the code snippet.

How do I correctly update settings via extension code?

回答1:

Solved it. The code I posted was actually throwing an error, but the update method is asynchronous and therefore the error was getting swallowed. By using async/await on the function, I was able to see the error, which was something like:

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

Basically, I had to update the exclude configuration in its entirety, not an individual key under it because those keys are just part of the configuration value -- they aren't actual configuration keys themselves. The working solution:

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)
}