I'm planning to write a Visual Studio Code extension and it need to save some information for example a counter. The user can press a shortcut to increase or decrease the counter and the value of the counter will be saved some where. Next time when the user starts Visual Studio Code, the extension can load the counter's last value. My question is, where is the proper place to store this info?
You're probably looking for the Memento
API. The ExtensionContext
has two different memento instances you can access:
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.
Both survive VSCode updates to my knowledge.
The value must be JSON-stringifyable
–
Dikdik When you have a global state that you want to see across all your VSCODE windows, you can use the globalState
from the extension's context.
I used this code in my extension to store a 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)
}
}
You should use the state mementos, but if you need a folder instead to put custom stuff in, you can instead use storageUri
https://code.visualstudio.com/api/references/vscode-api#ExtensionContext.storageUri and globalStorageUri
© 2022 - 2025 — McMap. All rights reserved.