create-react-app Typescript 3.5, Path Alias

The alias solution for craco or rewired create-react-app is react-app-alias for systems as: craco, react-app-rewired, customize-cra

According docs of mentioned systems replace react-scripts in package.json and configure next:

react-app-rewired

// config-overrides.js
const {aliasWebpack, aliasJest} = require('react-app-alias')

const options = {} // default is empty for most cases

module.exports = aliasWebpack(options)
module.exports.jest = aliasJest(options)

craco

// craco.config.js
const {CracoAliasPlugin} = require('react-app-alias')

module.exports = {
  plugins: [
    {
      plugin: CracoAliasPlugin,
      options: {}
    }
  ]
}

all

Configure aliases in json like this:

// tsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "example/*": ["example/src/*"],
      "@library/*": ["library/src/*"]
    }
  }
}

And add this file in extends section of main typescript config file:

// tsconfig.json
{
  "extends": "./tsconfig.paths.json",
  // ...
}

Edit - 20/3/20 - Above answer has a solution with a plugin.

Had the same problem. At the time of posting it is currently not supported as is.

This feature is still in development with the CRA team: https://github.com/facebook/create-react-app/pull/6116

If you edit the tsconfig CRA removes changes: https://github.com/facebook/create-react-app/issues/6269

There are some hacks in this thread: https://github.com/facebook/create-react-app/issues/5118 to get aliases working however require customization to the CRA setup which isn't suitable for my use case (using CRA as is).


In my case ,i solved this issue using craco and craco-alias

  1. Install craco and craco-alias npm install @craco/craco --save and npm i -D craco-alias

  2. Create tsconfig.paths.json in root directory

    {
        "compilerOptions": {
            "baseUrl": "./src",
            "paths": {
               "@components/*" : ["./components/*"]
             }
        }
    }
    
  3. Extend tsconfig.paths.json in tsconfig.json

    {
        "extends": "./tsconfig.paths.json",
        //default configs...
    } 
    
  4. Create craco.config.js in root direcory

      const CracoAlias = require("craco-alias");
    
      module.exports = {
         plugins: [
           {
              plugin: CracoAlias,
              options: {
                 source: "tsconfig",
                 // baseUrl SHOULD be specified
                 // plugin does not take it from tsconfig
                 baseUrl: "./src",
                 /* tsConfigPath should point to the file where "baseUrl" and "paths" 
                 are specified*/
                 tsConfigPath: "./tsconfig.paths.json"
              }
           }
        ]
      };
    
  5. in package.json swap "start": "react-scripts start" with "start": "craco start"