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
},
},
};
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
}
}
}
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
- Installing Dependencies :
cd your-react-app
npm i
-
Installing
vite-tsconfig-paths
plugin :
npm i vite-tsconfig-paths -D
-
Configure TypeScript :
In your
tsconfig.json
, streamline the path mappings:
"compilerOptions": {
// ...other options
"paths": {
"*": ["./src/*"]
}
}
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],
};
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';
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/*"]
}
}
}
Now, import from external folders:
import { Member } from 'types/user/members';
Benefits of the New Approach
Benefits of the New Approach
The streamlined setup with vite-tsconfig-paths
offers several advantages:
Simplified Configuration
Gone are the days of defining individual aliases for each module or component. The wildcard path mapping automatically covers your entiresrc
directory.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.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.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)
Solution for Vite 5.4 React Typescript project (bootstrapped with Bun).
The project has 3
tsconfig
files by defaultThe last one is used to set things up for React.
My project's structure is
I am able to use absolute imports like
@/commons/something
and'@/feature_x/path/to/something
from both withinsrc/
andtests/
.Here's my config file (pay attention to
paths
andinclude
entries)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";
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.