DEV Community

Mizan-Rifat
Mizan-Rifat

Posted on

Streamlining Absolute Imports in React with TypeScript and Vite

Absolute imports can significantly improve code readability and maintainability by eliminating the need for complex relative paths. If you're working on a React project with TypeScript and Vite, you've likely encountered solutions involving aliasing in vite.config.js and tsconfig.json. In this tutorial, I'll introduce a simpler approach using the vite-tsconfig-paths plugin. This method not only reduces setup complexity but also offers added convenience for your import workflow.

The Conventional Approach

Traditionally, achieving absolute imports in a React project involved a series of configurations that could become cumbersome as your project grew. This approach typically includes:

1.Setting Up Aliases
In vite.config.js, you'd configure aliases for specific
directories:

 import path from 'path';

 export default {
   // ...other config options
   resolve: {
     alias: {
       '@assets': path.resolve(__dirname, 'src/assets'),
       '@components': path.resolve(__dirname, 'src/components'),
       // ...other aliases
     },
   },
 };

Enter fullscreen mode Exit fullscreen mode

2.Configuring TypeScript Paths
In your tsconfig.json, you'd set up path mappings for these aliases:

 {
   "compilerOptions": {
     "baseUrl": ".",
     "paths": {
       "@/assets": ["./src/assets/*"],
       "@/components": ["./src/components/*"],
       // ...other paths
     }
   }
 }

Enter fullscreen mode Exit fullscreen mode

This approach becomes unwieldy as your project expands, requiring manual configuration for each module or component.

Introducing the Simplified Solution

With the vite-tsconfig-paths plugin, we can simplify this process while preserving the benefits of absolute imports.

  • Project Setup : Start by creating your React ts project with Vite:
npm create vite@latest your-react-app -- --template react-ts
Enter fullscreen mode Exit fullscreen mode
  • Installing Dependencies :
cd your-react-app
npm i
Enter fullscreen mode Exit fullscreen mode
  • Installing vite-tsconfig-paths plugin :
npm i vite-tsconfig-paths -D
Enter fullscreen mode Exit fullscreen mode
  • Configure TypeScript : In your tsconfig.json, streamline the path mappings:
 "compilerOptions": {
    // ...other options
    "paths": {
      "*": ["./src/*"]
    }
  }
Enter fullscreen mode Exit fullscreen mode

This change allows us to skip the need to declare individual alias definitions. With this setup, you can now import from any src folder without needing to declare modules for each specific folder.

  • Integration with Vite : In vite.config.js, integrate the plugin:
import tsconfigPaths from 'vite-tsconfig-paths';

export default {
  // ...other config options
  plugins: [tsconfigPaths(), react(), ...other plugins],
};

Enter fullscreen mode Exit fullscreen mode

Now, Vite will automatically use your TypeScript path settings to figure out how to find the files you want to import.

Seamless Absolute Imports

With the setup in place, you can now use absolute imports effortlessly in your code:

import Button from 'components/Button';
import logo from 'assets/logo.png';
import useCustomHook from 'hooks/useCustomHook';
Enter fullscreen mode Exit fullscreen mode

External Module Imports

Need to import modules from a folder outside the src directory? It's a breeze:

Extend your tsconfig.json:

{
  "compilerOptions": {
    // ...other options
    "paths": {
      "*": ["./src/*"],
      "types/*": ["./types/*"]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Now, import from external folders:

import { Member } from 'types/user/members';
Enter fullscreen mode Exit fullscreen mode

Benefits of the New Approach

Benefits of the New Approach
The streamlined setup with vite-tsconfig-paths offers several advantages:

  1. Simplified Configuration
    Gone are the days of defining individual aliases for each module or component. The wildcard path mapping automatically covers your entire src directory.

  2. Reduced Maintenance
    As your project grows, you won't need to continuously update alias configurations. The simplified path mapping remains effective regardless of the new additions.

  3. Seamless Transition
    Moving from the conventional approach to this new method is straightforward. You can gradually transition by leveraging the wildcard path and updating specific paths as needed.

  4. Consistency with TypeScript
    Since we're utilizing TypeScript's native path mapping, our imports remain aligned with the development experience provided by TypeScript.

Conclusion

Simplify your React project's import workflow with the vite-tsconfig-paths plugin. By harnessing the power of TypeScript's path mapping, you can achieve cleaner, more organized imports without the need for complex alias configurations. This approach not only reduces setup overhead but also enhances the maintainability and readability of your codebase as it scales.

Give this approach a try in your projects and experience the benefits of streamlined absolute imports.

Top comments (3)

Collapse
 
jvmdo profile image
João Oliveira • Edited

Solution for Vite 5.4 React Typescript project (bootstrapped with Bun).

The project has 3 tsconfig files by default

tsconfig.json
tsconfig.node.json
tsconfig.app.json
Enter fullscreen mode Exit fullscreen mode

The last one is used to set things up for React.

My project's structure is

src/
   assets/
   commons/
   features/
      feature_x/
      feature_y/
      feature_z/
tests/
Enter fullscreen mode Exit fullscreen mode

I am able to use absolute imports like @/commons/something and '@/feature_x/path/to/something from both within src/ and tests/.

Here's my config file (pay attention to paths and include entries)

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "noEmit": true,
    "jsx": "react-jsx",
    "paths": {
      "@/*": ["./src/*", "./src/features/*"],
      "@/tests/*": ["./tests/*"]
    },

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src", "tests"]
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mindsurfer profile image
Mindsurfer7 • Edited

im sorry bro but this dont work(

plugins: [
tsconfigPaths(),
react(),
svgr(), //{ exportAsDefault: true }
],

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

and when i import { GoogleProfile } from 'entities/GoogleProfile/types/GoogleProfile';
i get Uncaught SyntaxError: indirect export not found: GoogleProfile

If i open this file by clickin from console i ll see this: import { GoogleProfile } from "/src/entities/GoogleProfile/types/GoogleProfile.ts";

Collapse
 
mizanrifat profile image
Mizan-Rifat

It is working fine for me, so I have created a test Git repository for you. Here, you can check.
And please ensure that in tsconfig.json file, you have added the
"paths": {
"*": ["./src/*"]
}

code inside the compilerOptions property, not in the root.