vite logo react logo ts logo
Amir ShabanWeb Developer28 Dec, 2024

How to create absolute Imports with Vite, ReactJS and Typescript

vite logo react logo ts logo

Introduction

This guide will walk you through setting up absolute imports in a Vite React + Typescript application. You’ll learn how to set up your project, configure the vite.config.js file to support absolute imports as well as configuring the tsconfig.json file, use absolute paths for importing components. By the end, you’ll be able to effectively configure and utilize absolute imports in your Vite React app.

The Problem

Relative imports are the default method for referencing source files in JavaScript projects. However, as the codebase grows larger and more complex, finding the correct file for edits or debugging can become challenging. That's where Absolute imports comes in. It offers a straightforward and consistent approach making it easier to organize and maintain your project.

Worst case, importing components become so long and hard to track which files they are found in, making the code look rough and shabby.

App.ts
import Main from "../../../components/layouts/Main";

function App() {
  return <Main/>
}

export default App;

Setting Up Vite and React

Vite uses TypeScript's tsconfig.json paths feature for setting up aliases. Install the @types/node package to make configuration seamless:

sh
npm install -D @types/node

Modify your vite.config.ts file to include the resolve.alias property. The @ symbol is set as an alias for the src directory. You can replace it with any other symbol or name as needed.

vite.congfig.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "@": resolve(__dirname, "src"),
    },
  },
});

Setting Up Typescript

Update tsconfig.json (or jsconfig.json for JavaScript projects): Add the paths field to ensure TypeScript recognizes the alias.

tsconfig.json
{
  "compilerOptions": {
    //ts configs

    "baseUrl": ".",
    "paths": { "@/*": ["./src/*"] }
  },
  "include": ["src"]
}

Conclusion

By following this tutorial, you've learned how to set up absolute imports in a Vite React project to simplify and organize your code structure. Using path aliases like @ for your src directory, you can avoid cumbersome relative paths and make your imports more intuitive and maintainable.

App.ts
import Main from "@/components/layouts/Main";

function App() {
  return <Main/>
}

export default App;

TypescriptNodeJSReactJS