如何保留 vscode 扩展的信息?

How to persist information for a vscode extension?

我打算写一个 Visual Studio 代码扩展,它需要保存一些信息,例如计数器。用户可以按快捷方式增加或减少计数器,计数器的值将保存在某个地方。下次当用户启动 Visual Studio 代码时,扩展可以加载计数器的最后一个值。我的问题是,存储此信息的正确位置在哪里?

您可能正在寻找 Memento API. The ExtensionContext 您可以访问的两个不同的纪念品实例:

  • workspaceState

    A memento object that stores state in the context of the currently opened workspace.

  • globalState

    A memento object that stores state independent of the current opened workspace.

据我所知,两者都存活 VSCode 更新。

当您想要在所有 VSCODE windows 中查看全局状态时,您可以使用扩展上下文中的 globalState

我在我的扩展中使用了这段代码来存储 string:


async function activate (context) {
  const state = stateManager(context)
  
  const {
    lastPaletteTitleApplied
  } = state.read()

  await state.write({
    lastPaletteTitleApplied: 'foo bar'
  })

}


function stateManager (context) {
  return {
    read,
    write
  }

  function read () {
    return {
      lastPaletteTitleApplied: context.globalState.get('lastPaletteApplied')
    }
  }

  async function write (newState) {
    await context.globalState.update('lastPaletteApplied', newState.lastPaletteTitleApplied)
  }
}