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

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

·

2 min read

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.

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

The Above imports will be changed to as below

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.

mark-directory

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

jetbrains-ide

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.

Did you find this article valuable?

Support Nilanth's Blog by becoming a sponsor. Any amount is appreciated!