Absolute Imports: Vite TypeScript 2022
Tarik Čaplja
Posted on October 17, 2022
Hello. Everyone, I was trying to configure absolute import with Vite and TypeScript and I lost one day trying to configure it. I tried every Stackoverflow solution but non of them worked. So I decided to share with everyone this simple solution.
Step 1 - vite.config.ts
To configure absolute imports in vite we need to edit config file. Here is config file.
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
build: {
// Here you define your build directory
outDir: "./server/dist/",
},
// Here is config for absolute imports
resolve: {
alias: {
// You can configure this in any way you like it
// Below is my example
"@components": "./src/components/",
"@hooks": "./src/hooks/",
"@utils": "./src/utils/",
},
},
});
Step 2 - tsconfig.json
This is tricky part, not because it is hard to configure, but because it is very import to have * (wildcard) after defined path.
{
"compilerOptions": {
"baseUrl": ".",
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
// To configure import you need to add paths config
"paths": {
// ⭐️ It is very important to put /* in both key and value config
"@components/*": ["./src/components/*"],
"@utils/*": ["./src/utils/*"],
"@hooks/*": ["./src/hooks/*"]
}
},
"include": ["src"],
}
Valid config
"paths": {
"@components/*": ["./src/components/*"],
"@utils/*": ["./src/utils/*"],
"@hooks/*": ["./src/hooks/*"]
}
Invalid config
"paths": {
"@components": ["./src/components"],
"@utils": ["./src/utils"],
"@hooks": ["./src/hooks"]
}
Still have problem?
If you use VS Code try to restart TS server by pressing CMD+SHIFT+P
and type TypeScript Restart TS Server
.
💖 💪 🙅 🚩
Tarik Čaplja
Posted on October 17, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
githubcopilot AI Innovations at Microsoft Ignite 2024 What You Need to Know (Part 2)
November 29, 2024