How do I configure VSCode to offer vitest auto imports?
Asked Answered
S

2

8

In VSCode, I have a very small project with vite and vitest installed. With vitest, unlike with jasmine or jest, you need to explicitly import symbols like describe, it, expect etc.

Unfortunately, VS Code does not even offer auto-import (cmd + .):

VSCode after pressing cmd+.

I have Vitest extension installed if that matters (VSCode is not my primary IDE, so I might be missing something).

How do I configure my environment so that I can easily import those functions?

Scowl answered 19/3, 2023 at 10:23 Comment(2)
In my case it offers autocomplete from vitest package. Is it not enough for you or it doesn't work?Hedrick
@RomanBatsenko As you see, it doesn't work: "No code actions available"Scowl
R
2

Setting up automatic imports for Vitest may help. Try to do the following

  • Open VSCode settings
  • Search for "Auto Import" in the search bar
  • Scroll down to the "JavaScript › Auto Import: Custom" section and click on the "Edit in settings.json".
  • Add the following config:

"javascript.suggest.autoImports": true,
"javascript.preferences.importModuleSpecifier": "relative", "javascript.preferences.importModuleSpecifiers": { "@vitest": "./node_modules/vitest/src" }

  • Save and restart vscode
Rann answered 21/3, 2023 at 11:12 Comment(1)
Thanks. I did it for typescript actually, the last setting importModuleSpecifiers doesn't seem to be recognized (1.76.2), but it does work anyway. :)Scowl
C
3

First, no VS Code changes are necessary.

Here's a reference to their documentation. Vitest Config Globals

I'll provide an example with a minor custom vite configuration with TypeScript.

// vite.config.ts
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [tsconfigPaths()],
})
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import config from './vite.config';

export default defineConfig({
  ...config,
  test: {
    globals: true,
  }
});
// tsconfig.json
{
  "compilerOptions": {
    "types": ["vitest/globals"],
  }
}
Cyte answered 1/2 at 15:35 Comment(0)
R
2

Setting up automatic imports for Vitest may help. Try to do the following

  • Open VSCode settings
  • Search for "Auto Import" in the search bar
  • Scroll down to the "JavaScript › Auto Import: Custom" section and click on the "Edit in settings.json".
  • Add the following config:

"javascript.suggest.autoImports": true,
"javascript.preferences.importModuleSpecifier": "relative", "javascript.preferences.importModuleSpecifiers": { "@vitest": "./node_modules/vitest/src" }

  • Save and restart vscode
Rann answered 21/3, 2023 at 11:12 Comment(1)
Thanks. I did it for typescript actually, the last setting importModuleSpecifiers doesn't seem to be recognized (1.76.2), but it does work anyway. :)Scowl

© 2022 - 2024 — McMap. All rights reserved.