Today in this short article let's quickly learn how to set up path aliases in your React application. Avoid boring long imports in your app and start using path aliases now.
Pre-requisites
Must have a React app with vite. If you are still using CRA, checkout my guide to migrate your app to vite.
For Javascript Projects
- Update your vite config You have to update your vite config to make your aliases work.
Paste the following contents -
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"@components": path.resolve(__dirname, "./src/components"),
"@pages": path.resolve(__dirname, "./src/pages"),
"@forms": path.resolve(__dirname, "./src/forms"),
"@utils": path.resolve(__dirname, "./src/utils"),
"@providers": path.resolve(__dirname, "./src/providers"),
"@assets": path.resolve(__dirname, "./src/assets"),
},
},
plugins: [react())],
});
You can add your own folder according to your need. Likes hooks
,context
and etc.
-
For Javascript/Typescript project, create a
jsconfig.json
ortsconfig.json
(For Typescript Project) file in the root of your project. This step is necessary to make sure vs code intellisense works properly.
Paste the following contents -
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@components/*": ["./src/components/*"],
"@pages/*": ["./src/pages/*"],
"@assets/*": ["src/assets/*"],
"@forms/*": ["src/forms/*"],
"@providers/*": ["src/providers/*"],
"@utils/*": ["src/utils/*"]
}
}
}
This file will help your code editor intellisense to recommend you the path aliases during import.
That's all, now you can import a component like
import MyComponent from "@components/MyComponent";
Thank you for reading this article. π
Please share and follow for more dev content. π
Top comments (0)