In order for this to work, you need to tell TypeScript and Vite how they should resolve it.
Step 1. In tsconfig.app.json and in tsconfig.node.json just add the paths to the compilerOptions. Should look something like:
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"],
"@components/*": ["./src/components/*"],
}
}
}
Step 2. For vite.config, you should have:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue' // or -react or -svelte or ...
//@ts-expect-error Suppressing 'cannot find' error
import path from "path";
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
//@ts-expect-error Suppressing 'cannot find' error
"@": path.resolve(__dirname, "src"),
//@ts-expect-error Suppressing 'cannot find' error
"@components": path.resolve(__dirname, "src/components"),
}
},
})
PS:
For some reason @types doesn't work (maybe it is a reserved keyword)
If you want to avoid duplicating path aliases, you can use the vite-tsconfig-paths plugin. While I personally prefer the previous approach, I understand the importance of the DRY principle—ultimately, it comes down to personal preference and project style.
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import tsconfigPaths from "vite-tsconfig-paths";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), tsconfigPaths()],
});