There are two problems here:
- Tell typescript how to resolve import path
- Tell vite how to build import path
You only tell typescript how to resolve, but vite don’t konw how to build. So refer to the official document resolve.alias, maybe this is what you want:
// vite.config.ts
{
resolve: {
alias: [
{ find: '@', replacement: path.resolve(__dirname, 'src') },
],
},
// ...
}
You can import path like this (or any module under ./src
):
import Test from "@/components/Test";
import bar from "@/foo/bar"
Moreover, you can use vite plugin vite-tsconfig-paths
directly, it makes you don’t have to manually configure resolve.alias
Follow the instructions below:
-
Install
vite-tsconfig-paths
as dev dependency -
Inject
vite-tsconfig-paths
using the vite.config.ts module
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [tsconfigPaths()],
})