No More ../../../ Import in React
Nilanth

Nilanth @nilanth

About: Full Stack Developer | ReactJS | Redux | NextJS | Laravel | PostgreSQL | AWS | Follow on Twitter for daily updates | Let’s make the web. Faster 🚀

Location:
India
Joined:
Jan 16, 2021

No More ../../../ Import in React

Publish Date: Aug 15 '21
1552 52

Steps to configure absolute Import in Create React App without any third-party packages.

Are you importing components like ../../../../somecomponents? Then you should update to Absolute imports. 

Benefits of Absolute Import

  1. You can move your existing code to other components with imports without any changes.
  2. You can easily identify that where the component is actually placed using the import path.
  3. Cleaner Code.
  4. Easier to write.

Configure Absolute Import

To support absolute import create a file named jsconfig.json in your root directory and add the below code.



{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}


Enter fullscreen mode Exit fullscreen mode

Now let's convert the relative imports in the below component to Absolute Import



import React from 'react';
import Button from '../../components/Button';
import { red } from '../../utils/constants/colors';

function DangerButton(){
  return <Button color={red} />;
}

export default DangerButton;


Enter fullscreen mode Exit fullscreen mode

The Above imports will be changed to as below



import React from 'react';
import Button from 'components/Button';
import { red } from 'utils/constants/colors';

function DangerButton(){
  return <Button color={red} />;
}

export default DangerButton;


Enter fullscreen mode Exit fullscreen mode

Now our imports are clean and understandable. 

Configuring in JET Brains IDEs

  • For JET Brains IDEs like WebStorm, PhpStorm, RubyMine and etc, we need to add some additional configurations as below to support Absolute import

Right-click the src folder and select Mark Directory as and Click Resource Root.

Resource Root

  • Next select Preferences -> Editor -> Code Style -> JavaScript -> Imports and Check Use paths relative to the project, resource or source roots and Click Apply.

ide-resource

VS Code

No Changes need to be done in VS Code. It will automatically import the config from jsconfig.json file.

Resources

  1. VS Code jsconfig.json
  2. JET Brains CodeStyle

Conclusion

Absolute imports make the component more readable and clean. I hope you have found this useful. Thank you for reading.

Get more updates on Twitter.

You can support me by buying me a coffee ☕

eBook

Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples

ReactJS Optimization Techniques and Development Resources

More Blogs

  1. Laravel Sanctum Authentication for React App Using Breeze
  2. Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS
  3. Don't Optimize Your React App, Use Preact Instead
  4. Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support
  5. 10 React Packages with 1K UI Components
  6. Redux Toolkit - The Standard Way to Write Redux
  7. 5 Packages to Optimize and Speed Up Your React App During Development
  8. How To Use Axios in an Optimized and Scalable Way With React
  9. 15 Custom Hooks to Make your React Component Lightweight
  10. 10 Ways to Host Your React App For Free
  11. How to Secure JWT in a Single-Page Application

Comments 52 total

  • Tosin Ayodele
    Tosin AyodeleAug 15, 2021

    Interesting. Thanks for the tip. Looking forward to implementing this in my next project.

  • Kingkor Roy Tirtho
    Kingkor Roy TirthoAug 15, 2021

    But What will I do if I've to import from another file that is in the same folder but that folder is nested?
    E.g. src/service/backend/post/ is a folder. Inside that I have 2 modules but 1 imports another. So do I've to write it like import {aFunction} from "service/backend/post/module-2" ?

    Can I use relative import in that case?

    • Russell Sanders
      Russell SandersAug 15, 2021

      You can still use relative imports. This compiler option only adds to your abilities to do imports, it doesn't take away. you can still use import {aFunction} from "../module-2" and since it's relative, this will still work. The baseUrl option only applies to imports that are not relative, so relative imports still references from the current file

  • KaRthick
    KaRthickAug 15, 2021

    Searching this for a while but never thought this would be this much simpler 🎉

  • Mainak Das
    Mainak DasAug 15, 2021

    Perfect minimal tutorial/guide. Looking forward to implement this !

  • nosknut
    nosknutAug 15, 2021

    Pretty sure i used this in 2018

  • Shaquille Shaw
    Shaquille ShawAug 15, 2021

    Great read, I'm sure I will use this soon!
    Quick question about the code, is it suppose to instead be :

    import Button from '../../components/Button';
    import { red } from '../../utils/constants/colors';

    I am curious because in doing this it would now allow the utils and the components folder to be both siblings of each other and both children folders of src.

  • Jazz Brown
    Jazz BrownAug 15, 2021

    Ooo neat.. nice post..

  • David Camarena
    David CamarenaAug 15, 2021

    Very nice and concise tip, thank you!

  • Saleh Muhammad
    Saleh MuhammadAug 15, 2021

    Nice one, But i think this approach is good when you are the only one maintainer of the codebase. For the whole team would suggest using webpack alias.

    webpack.js.org/configuration/resol...

    • Nilanth
      NilanthAug 16, 2021

      I think it can be used with n number of maintainer or n number of team also.
      As the Package with largest react community also uses this approach.
      FYR: github.com/ant-design/ant-design

      • Nathan Victor
        Nathan VictorAug 18, 2021

        You are correct, and the 5-line setting is tidy and simple. Either way, a team of any size would be using the same settings.

    • Aymen Marouani
      Aymen MarouaniAug 16, 2021

      Thanks for the tip, but how can I add this webpack alias when using create-react-app ?

      • Nilanth
        NilanthAug 16, 2021

        webpack alias not required for CRA. Above config is enough for CRA.

        • Aymen Marouani
          Aymen MarouaniAug 17, 2021

          There's also a library called craco that can override configuration for CRA

    • Dennis Groß (he/him)
      Dennis Groß (he/him)Aug 18, 2021

      I second webpack alias. I also suggest using an expressive prefix for the alias so everyone in the team understands that the import uses an alias.

      But Nilanth made a good job explaining why some sort of absolute imports makes your life easier.

  • Mostafijur Rahman
    Mostafijur RahmanAug 16, 2021

    Interesting. Thanks for the tip.

  • mhmtonrn
    mhmtonrnAug 16, 2021

    which theme of your ide

  • Renzo Gaspary
    Renzo GasparyAug 16, 2021

    Sorry if this sounds like a total newb question, but is there not a way to use @ in place of the root level like in vue.js?

  • Juanjo Lopez
    Juanjo LopezAug 16, 2021

    What about test files? Is Jest able to comply?

  • cl10k
    cl10kAug 16, 2021

    But how to convince the bundler (Webpack) to respect the settings in jsconfig?
    ———
    Webpack alias seems a bit stiff and fiddly…

  • АнонимAug 16, 2021

    [hidden by post author]

  • Nilanth
    NilanthAug 16, 2021

    Bundler will get the config from jsconfig, Not required to tell bundler separately.

  • Nilanth
    NilanthAug 16, 2021

    I have already mentioned this config is for Create React App (CRA)

  • James Stine
    James StineAug 16, 2021

    I tried this and had issues with resolving certain node modules in my project.

    • Nikita Makhov
      Nikita MakhovAug 18, 2021

      This can occur due to conflicting names. I use aliases like this: @utils, @components. I'm sure there will be case, where I will cross such namespace for module, but still there is no such case.

      • James Stine
        James StineAug 21, 2021

        I believe the issue was with the package react-i18next. This seems a bit too much for the project I'm working on, but it might be cool with starting a new project.

  • NamNguyen
    NamNguyenAug 17, 2021

    good tips, i think try it

  • Tomer Raitz
    Tomer RaitzAug 17, 2021

    Very cool! now we need to find a way for "global" import - all imports from one place. I really don't like the imports statements on all the files

  • Zen
    ZenAug 18, 2021

    We can use absolute path in Vite, like this:

    import style from '/src/lib/style.css'
    
    Enter fullscreen mode Exit fullscreen mode
  • Nicolás Danelón
    Nicolás DanelónAug 18, 2021

    I just love it

  • Lars Rye Jeppesen
    Lars Rye JeppesenAug 18, 2021

    Or use Typescript and use alias there.... React with JS is suck a mess

    • vrushank
      vrushankAug 19, 2021

      How do you setup alias using typescript? I'm having hard times setting up alias with typescript, It automatically overrides tsconfig settings when we run the project again and jsconfig won't work with typescript.

      • Lars Rye Jeppesen
        Lars Rye JeppesenAug 19, 2021

        Sorry I don't use jsconfig at all, we use pure TSC (Typescript) compiler and we don't use Babel for our projects.

        For pure typescript it's just a configuration in tsconfig.json as you mentioned. I am not sure what's going on with your setup, unfortunately
        Cheers

        • vrushank
          vrushankAug 19, 2021

          I understand, I just want to know that setting how you setup alias using tsconfig in CRA.

          • Lars Rye Jeppesen
            Lars Rye JeppesenAug 19, 2021

            I'm sorry I misunderstood you.
            We're not using React so I can't say how it's done there, unfortunately. So sorry

  • Renan "Firehawk" Lazarotto
    Renan "Firehawk" LazarottoAug 18, 2021

    This will definitely come in handy for the React project I'm working on (my portfolio! hopefully I'll have enough time to finish it one day...), and quite frankly, imports are one of my main issues with JavaScript and I sometimes still quite don't get them.

  • Elizabeth
    ElizabethAug 18, 2021

    Thanks for sharing! This really come in handy

  • Gene
    GeneAug 19, 2021

    I'd use babel-module-resolver for this case. Much neater.

    import {Button} from '../../components/Button';
    // vs
    import {Button} from '@components'
    
    Enter fullscreen mode Exit fullscreen mode
  • Jitu Chauhan
    Jitu ChauhanAug 19, 2021

    Thank you for sharing this amazing.

  • Dave Stewart
    Dave StewartAug 19, 2021

    You may also want to check out Alias HQ:

    github.com/davestewart/alias-hq/

    It manages aliases, has support for React and various other packages, and even has a CLI to refactor your code.

  • vrushank
    vrushankAug 19, 2021

    Thanks for sharing, This is really great but It will even greater if we can use alias without ejecting in CRA. Do you have any method to implement alias using CRA?

    Also if you have any idea implmenting the same with typescript, please share the same or update the post.

    Cheers~

    • Nilanth
      NilanthAug 19, 2021

      Hey, above method is for CRA only. For typescript use tsconfig.json file instead of jsconfig.json

      • vrushank
        vrushankAug 19, 2021

        I know this for CRA but do you know how to setup alias?

  • César
    CésarAug 19, 2021

    Interesting️‍🔥️‍🔥

  • Atharva Shankar Ahvad
    Atharva Shankar AhvadAug 21, 2021

    t noice

  • Vico
    VicoAug 30, 2021

    what's your JetBrains font?

  • Pavan C
    Pavan CSep 10, 2021

    Little lately, after using this config, I found out that when you try to import render function from react testing library, it uses require syntax but not the import syntax. Has anyone experienced this? It is same with all the imports in the test cases.

Add comment