Creating path alias in React project

/* Previous */
import { Component } from '../../../directory/sub-directory'

/* Now */
import { Component } from '@directory/sub-directory'

Using CRACO

CRACO helps us override internal configuration without touching Webpack and its complexities.

npm i @craco/craco 

In package.json file, replace react-scripts to craco

"start": "craco start",
"build": "craco build",
"test": "craco test",

Install craco-alias

npm i craco-alias --save-dev

Setup craco.config.js file

const cracoAlias = require("craco-alias");

module.exports = {
  plugins: [
    {
      plugin: cracoAlias,
      options: {
        source: "jsconfig",
        baseUrl: "./"
      }
    }
  ]
};

Create jsconfig.json file if it doesnt exist; for Typescript it will be tsconfig.json

{
	"compilerOptions": {
		"baseUrl": ".",
		"paths": {
			"@/*": [
				"src/*"
			]
		}
	}
}

Run npm run start, if all goes well there shouldn’t be any errors during import.

Author: Soumil Roy

I'm a Frontend Engineer currently building expertise in React, TypeScript & GraphQL

Leave a Reply

Your email address will not be published.