DEV Community

Orinda Felix Ochieng
Orinda Felix Ochieng

Posted on • Updated on

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

Thumbnail

TLDR,

First you need to create React application 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
You'll also need craco-alias to resolve the alias paths

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

Create a file named craco.config.js and add the following code.

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

module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: "tsconfig",
        baseUrl: "./src",
        tsConfigPath: "./tsconfig.paths.json",
      },
    },
  ],
};


Enter fullscreen mode Exit fullscreen mode

Create a new file namedtsconfig.paths.json and add the following

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@components/*": ["./components/*"],
      "@pages/*": ["./pages/*"],
      "@api/*": ["./api/*"],
      "@base/*": ["./*"]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Then in your tsconfig.json add this line

{
  "compilerOptions": {
    ...
  },
  "extends": "./tsconfig.paths.json",
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

My directory structure

Directory structure

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 using 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

Top comments (0)