bob.ts
Posted on August 23, 2021
I was working on a side-project over the last few days and was working with a jsconfig.js
file I found reference to that was supposed to allow for aliasing a folder in a create-react-app
project.
Everything I tried failed, so I went with this option that worked remarkably well.
The Goal
The goal is to provide path aliases for a react project. This makes code look cleaner and easier to understand.
Original Code ...
import Header from './features/header/header.component';
import Footer from './features/footer/footer.component';
The Goal I wanted to achieve ...
import Header from '@features/header/header.component';
import Footer from '@features/footer/footer.component';
With a larger project, this is something that becomes almost critical.
Requirements
For this project, I went with react-app-rewired and react-app-rewire-alias
Installation can be done via Yarn ...
yarn add --dev react-app-rewired react-app-rewire-alias
... or NPM ...
npm install --save-dev react-app-rewired react-app-rewire-alias
Setup
Then, in the root directory, a file called config-overrides.js
needs to be created with the following code ... the aliases may change for your specific project, but this gives the idea.
const { alias } = require('react-app-rewire-alias');
module.exports = function override(config) {
alias({
'@core': 'src/core',
'@features': 'src/features',
'@pages': 'src/pages',
'@shared': 'src/shared'
})(config);
return config;
};
The alias
imported allows for a simple object with key/value pairs to provide alias/path options for a project.
The next step is to adjust the scripts
inside the package.json
file. In most locations where the code reads react-scripts
, it should be replaced with react-app-rewired
.
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
... becomes ...
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
Conclusion
At this point, the project code can now use the new aliases as we saw in the goal above.
import Header from '@features/header/header.component';
import Footer from '@features/footer/footer.component';
A simple npm start
will verify the functionality at this point.
Posted on August 23, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.