module aliases in react

Mohamed Zaki
Feb 18
1 min read
post_comment2 Comments
post_like1 Likes

For a React project using TypeScript and Vite, you can configure module aliases in the vite.config.js (or vite.config.ts if you're using TypeScript for Vite config) and tsconfig.json files. Here's how to set up an alias for the src folder:

#Step 1: TypeScript Configuration

Edit your tsconfig.json to include the baseUrl and paths options under compilerOptions. To create an alias @ that points to the src directory:

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

#Step 2: Vite Configuration

In your vite.config.js or vite.config.ts, configure the resolve alias. Here's how you can do it in JavaScript:

import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'path'; // export default defineConfig({ plugins: [react()], resolve: { alias: { '@': path.resolve(__dirname, './src'), }, }, });

If you're using TypeScript for your Vite configuration, the setup is similar, just ensure your vite.config.ts is properly typed.

#Step 3: Restart Vite Server

After making these changes, restart your Vite development server to apply the configuration changes.


Now, you can import any file from the src folder using the @ alias, like so:

import MyComponent from '@/components/MyComponent';

This setup simplifies imports in your project by allowing you to refer to the src folder directly with @, making your import statements cleaner and more manageable.