reactjstypescriptvite

Absolute path not working in Vite project React TS


I'm struggling to get absolute path to work in a Vite react-ts project.

Here's how I created the project

npm init @vitejs/app
npx: installed 6 in 1.883s
√ Project name: ... test-vite
√ Select a framework: » react
√ Select a variant: » react-ts

Then I added baseUrl to tsconfig.json based on the TS official doc:

{
  "compilerOptions": {
    "baseUrl": "./src",
    ...

followed by adding a simple component (T:\test-vite\src\components\Test.tsx)

import React from "react";

const Test = () => <h1>This is a Test.</h1>;

export default Test;

Finally I import the Test component in App.tsx
but it won't let me use absolute path:

import Test from "components/Test";

I get this error enter image description here

whereas if I use relative path, the app works in dev & build mode without any error:

import Test from "./components/Test";

How can I make absolute path work in the project?


Solution

  • There are two problems here:

    You only tell typescript how to resolve, but vite don't know 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:

    1. Install vite-tsconfig-paths as dev dependency

    2. 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()],
    })