How to use module alias in React js (`CRA`)

forinda

Orinda Felix Ochieng

Posted on March 26, 2022

How to use module alias in React js (`CRA`)

TLDR,

Thumbnail

First you need to create React applicatin using Create React App (CRA)

$ npx create-react-app testing-alias --template typescript
# Or 
$ yarn create react-app testing-alias --template typescript
Enter fullscreen mode Exit fullscreen mode

Next Well add an override to the default webpack
We'll use craco to run our application instead of react-scripts

$ npm i craco
#Or
$ yarn add craco
Enter fullscreen mode Exit fullscreen mode

Once craco is installed, Create a craco.cofig.js
Then install tsconfig-paths-webpack-plugin for loading the typescript paths

$ yarn add tsconfig-paths-webpack-plugin
#Or
$ npm i tsconfig-paths-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Add the folling to your craco.config.js

const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");

module.exports = {
  webpack: {
    plugins: [new TsconfigPathsPlugin()],
  },
};
Enter fullscreen mode Exit fullscreen mode

Add the following to your tsconfig.json

{
 "compilerOptions":{
    "baseUrl": "./src",
    "paths": {
      "@component/*": ["./src/@components/*"],
      "@pages/*": ["./src/@pages/*"],
      "@utils/*": ["./src/@utils/*"],
      "@hooks/*": ["./src/@hooks/*"],
      "@app:state/*": ["./src/state/*"]
    }
  },
  "include": ["src"]
}

Enter fullscreen mode Exit fullscreen mode

Then in your tsconfig.json add the following to match our directory structure

Enter fullscreen mode Exit fullscreen mode

Directory structure
AppNav component in the  raw `@components` endraw  directory

Finally modify your package.json

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

In the App.{js|ts} you import the given component and the run your application using yarn start or npm start

In conclusion we've learnt to add module aliasing to our react js packages ging absolute imports. It's easier this way given the growth of your application may have and also having similar names in either pages or components conflict is avoided. It's easier this way since you don't need to eject your react app

Thanks to reading

💖 💪 🙅 🚩
forinda
Orinda Felix Ochieng

Posted on March 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related