Create path aliases in React js
This tutorial will guide you to create path aliases for your react project. Creating path aliases for assets or components makes look code cleaner and prettier. For example, look at the below before and after image.
Isn’t it look cleaner? This fits great if your project is big and you need to import lots and lots of files and components to your file. So let us get started on how to create path aliases in react js.
Requirements
- Open the terminal in your project root directory and install the react-app-rewired and react-app-rewire-alias as a dev dependency.
npm install react-app-rewired react-app-rewire-alias --save-dev
2. Now inside the root directory create a file with the name config-overrides.js and paste the below code.
Here we are first importing {alias} from react-app-rewire-alias. After that, we are adding an object with key-value pairs inside alias where the key is your path definition and the value is the path. You can add multiple key-value pairs for different definition and path.
3. Now open your package.json file and ‘Flip’ the existing calls from react-scripts
to react-app-rewired
4. Now you can use your new aliases inside your React js project.
5. Start your project npm start
to check if it’s working or not.
Below is the Github repository for reference.