DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Clean Up Your Imports using Absolute Imports & Alias on React apps (Next.js, CRA, and React-Vite)
Theodorus Clarence
Theodorus Clarence

Posted on • Updated on

Clean Up Your Imports using Absolute Imports & Alias on React apps (Next.js, CRA, and React-Vite)

Absolute Import is a great way to clean up your imports

Setting up absolute imports can be a lot of pain to search on the internet, I spend quite some time to make this work, so here is all of the setup I use to make it work, all in one blog.

The problem

This is the usual way of importing with .. operator to go back 1 folder:

import Nav from '../../components/Nav';
Enter fullscreen mode Exit fullscreen mode

In larger projects, this could be a nightmare.

And this is the cleaner import after using absolute import and alias:

import Nav from '@/components/Nav';
Enter fullscreen mode Exit fullscreen mode

You can also change the @ symbol to whatever you want. Neat right?

There are 4 react apps setup I found on the internet, and I summarized all of those for you.

  1. For Next.js Apps
  2. For Create React App using Craco
  3. For Create React App without using Craco (alias not available)
  4. For React + Vite

For Next.js

  1. Add this to root with the filename of jsconfig.json
{
  "compilerOptions": {
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "@/*": ["*"],
      "@/components/*": ["components/*"],
      "@/styles/*": ["styles/*"]
      // add more folders here
    }
  },
  "exclude": ["node_modules", ".next"]
}
Enter fullscreen mode Exit fullscreen mode

Or you can just use my Next.js & Tailwindcss starter template with all of the boilerplate set up.

[edit] It turns out in Next.js we can just write the first path like so:

{
  "compilerOptions": {
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "@/*": ["*"]
    }
  },
  "exclude": ["node_modules", ".next"]
}
Enter fullscreen mode Exit fullscreen mode

Credits to Kutsan Kaplan, I am not removing the original one, in case there are some problems about auto imports or F12 look up.


For Create React App using Craco

Only available if using Craco, usually we use Craco when also using Tailwind CSS, so no extra setup.

  1. Add this to root with the filename of jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src",
    "jsx": "preserve",
    "paths": {
      "@/*": ["./src/*"],
      "@/components/*": ["./components/*"],
      "@/pages/*": ["./pages/*"],
      "@/contexts/*": ["./contexts/*"],
      "@/routes/*": ["./routes/*"]
    }
  },
  "exclude": ["node_modules", "build"]
}
Enter fullscreen mode Exit fullscreen mode

You need to update this file every time you create a new folder

  1. And in craco.config.js
const path = require('path');

module.exports = {
  // ...existing code
  webpack: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

For Create React App without using Craco

Create React App only supports absolute import, but no alias

  1. Add in jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

The absolute import will only remove the relative path, but won't add @/ alias.

For example:

import Button from 'components/Button';
Enter fullscreen mode Exit fullscreen mode

For React Vite

(might be outdated)

  1. Add this to root with the filename of jsconfig.json
{
  "compilerOptions": {
    "jsx": "preserve",
    "baseUrl": "./src",
    "paths": {
      "@/components/*": ["./components/*"],
      "@/pages/*": ["./pages/*"],
      "@/routes/*": ["./routes/*"],
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

You need to update this file every time you create a new folder

  1. Also add this to root with the filename of vite.config.js
import { defineConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
const path = require('path');

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: [{ find: '@', replacement: path.resolve(__dirname, '/src') }],
  },
  plugins: [reactRefresh()],
});
Enter fullscreen mode Exit fullscreen mode

Or you can just use my Vite + React + Tailwindcss starter template


Originally posted on my personal site, find more blog posts and code snippets library I put up for easy access on my site πŸš€

Top comments (15)

Collapse
 
kutsan profile image
Kutsan Kaplan

Wasn't this enough? No need to add an entry everytime you create a folder.

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

Enter fullscreen mode Exit fullscreen mode
Collapse
 
theodorusclarence profile image
Theodorus Clarence Author • Edited on

Oh cool, just tried it and it works on Next.js, I remember it has some issue for the F12 look up but I think there is no problem now! Thanks for your addition, updated the blog.

It kinda messes with CRA auto import using that approach, will update if I found anything.

Collapse
 
abhayrana profile image
abhay-rana • Edited on

i have two jsconfig.json flie in my project one is for my reactjs and one is for my nodejs project
and it is always good to use special character before the folder path
the config i user for my backend :-

//the config i use for my backend :-
{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "~/*": ["*"]
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
//the config i use for my frontend :-

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

Enter fullscreen mode Exit fullscreen mode

Image description

Collapse
 
kutsan profile image
Kutsan Kaplan

Looks good but I think tilde-slash prefix (~/) shouldn't be used for project-scoped aliases. ~/ means home directory for current user on unix-like systems. So, it is looking like an absolute path to me at the first glance.

Collapse
 
monkeyalex profile image
MonkeyAlex

Great article.
Would it be possible to configure vite to understand absolute path WITHOUT using a prefix like (@)?

My vite project is created as React JS (not TS).

Previously with CRA + WebPack, I was able to specify this:

import Main from "Main";
import MyComponent from "components/level2/MyComponent";
Enter fullscreen mode Exit fullscreen mode

where my jsconfig.json looks like this:

{
  "compilerOptions": {
    "target": "es2020",
    "baseUrl": "src/"
  },
  "exclude": ["node_modules", "build"]
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
consoletvs profile image
Erik C. ForΓ©s

Sorry but what's wrong with?

// tsconfig.json or jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "."
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
theodorusclarence profile image
Theodorus Clarence Author

It's really just preference

Collapse
 
mlnzyx profile image
R. Maulana Citra

Awesome article bro, very helpful, thanks for sharing!

Collapse
 
rayhanns04 profile image
Hans

Hii bro" i have fixed for new problem on React Vite without TS, just just chillin add ./ before src on alias (vite.config.js), and it will solve your problem.

Image description

Image description

Collapse
 
yaireo profile image
Yair Even Or

@vitejs/plugin-react-refresh is deprecated, maybe consider updating the article and removing it?

Collapse
 
snxk profile image
Sayan Mallick

How to implement this in typescript? Do I just edit the tsconfig.json?

Collapse
 
omkar_k45 profile image
Omkar Kulkarni

Yes. That would take care of it.

Collapse
 
mellunar profile image
mellunar • Edited on

I'm getting a MIME not allowed error when I change filepath to '@/filepath'
React JS + Vite

Collapse
 
hasnaindev profile image
Muhammad Hasnain

This does not help with syntax highlighting, right?

Collapse
 
ijash profile image
Jastria Rahmat

For Create React App without using Craco in latest version (v5.0.1) , absolute import doesn't work. it's a bug. please revise the post. github.com/facebook/create-react-a...

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.