0

I created a Vue / React / Svelte + Typescript + Vite project using:

npm create vite@latest

and have the following files in my project:

...
tsconfig.app.json
tsconfig.json
tsconfig.node.json
vite.config.ts

How do I get to setup absolute paths ?

so I can use something like this:

import TodoList from '@components/TodoList'
import type { Todo } from "@/types/Todo"

1 Answer 1

2

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()],
    });
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.