DEV Community

Cover image for Create Path Aliases in React
bob.ts
bob.ts

Posted on

Create Path Aliases in React

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';
Enter fullscreen mode Exit fullscreen mode

The Goal I wanted to achieve ...

import Header from '@features/header/header.component';
import Footer from '@features/footer/footer.component';
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

... or NPM ...

npm install --save-dev react-app-rewired react-app-rewire-alias
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

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"
},
Enter fullscreen mode Exit fullscreen mode

... becomes ...

"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject"
},
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

A simple npm start will verify the functionality at this point.

Discussion (0)