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
- You can move your existing code to other components with imports without any changes.
- You can easily identify that where the component is actually placed using the import path.
- Cleaner Code.
- 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"]
}
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;
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;
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
.
- Next select Preferences -> Editor -> Code Style -> JavaScript -> Imports and Check Use paths relative to the project, resource or source roots and Click Apply.
VS Code
No Changes need to be done in VS Code. It will automatically import the config from jsconfig.json
file.
Resources
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
- Laravel Sanctum Authentication for React App Using Breeze
- Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS
- Don't Optimize Your React App, Use Preact Instead
- Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support
- 10 React Packages with 1K UI Components
- Redux Toolkit - The Standard Way to Write Redux
- 5 Packages to Optimize and Speed Up Your React App During Development
- How To Use Axios in an Optimized and Scalable Way With React
- 15 Custom Hooks to Make your React Component Lightweight
- 10 Ways to Host Your React App For Free
- How to Secure JWT in a Single-Page Application