In this article, I would love to share with you how to use alias imports in create-react-app without using yarn eject
.
If you are unaware of Alias Imports it basically means renaming the absolute paths of your project folders, so that you can use the renamed path to import one module into another. So in other words we will try to resolve your imports from
import { Something } from '../../../components/SthComponent;
to
import { Something } from '@Components/SthComponent;
This approach would really help you to reduce time to import your modules quicker and would make the code look more clean.
Let's Get Started...
Create a new ReactJS project using the following command in your terminal.
npx create-react-app myreactproject // using npm
yarn create react-app myreactproject // using yarn
Install react-app-rewired and customize-cra packages
yarn add react-app-rewired customize-cra
Make sure to update your package.json.
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject" // do not change this
},
Finally, create a config-overrides.js file in the project root directory and add the following code -
const { override, addWebpackAlias } = require('customize-cra');
const path = require('path');
module.exports = override(
addWebpackAlias({
['@Components']: path.resolve(__dirname, './src/components'),
['@Images']: path.resolve(__dirname, './src/assets/images'),
['@Pages']: path.resolve(__dirname, './src/pages'),
['@Styles']: path.resolve(__dirname, './src/assets/styles'),
// add more directories
})
);
That's it. Restart your server and now you can use alias imports in your application.
A word of advice would be to make sure to use atleast the first letter in Uppercase to your alias name, so that it doesn't conflict with any node module. You may also use _
as a prefix instead of @
.
I highly recommend you to use my react-app-template where I already have set up most of the functionalities that you would need while creating a new ReactJS Project. It surely would save a considerable amount of time for you.
Hope that you found this article useful. The author would really appreciate if you could upvote this article and star the above repository.
Thank you for sparing your valuable time to read this.😃