Creating custom absolute paths with create-react-app

1.1k Views Asked by At

I've created a React project with typescript using create-react-app version 3.4.1. I'm trying to avoid the use of relative paths in my project. Here's a part of my project tree:

/
|_ public
|_ tests
|_ src
  |____ Scenarios
  |____ Components
        |____c

What I basically want is to be able to to do something like import '@components/c'. I've tried to add this part to my tsconfig.json file:

{

"compilerOptions": {
...
    "baseUrl": ".",
    "paths": {
      "*": ["src/*"],
      "tests": ["tests/*"],
      "public": ["public/*"],
      "@components/*": ["src/Components/*"],
      "@Scenarios/*": ["src/Scenarios/*"],
      },
...
   }
}

But every time I'm starting my app using yarn start my tsconfig deletes this part of my code (eveything but my "baseUrl" part). As far as I know since version 3 of react-create-app, solved this problem partially with enabling baseUrl property to affect the imports' root dir. But I couldn't find anywhere a working solution to set absolute paths from tsconfig path directory. The partial solution doesn't work for me as I'm probably going to import stuff from public directory.

I did try this solution from last year but it wouldn't work for me. Did anyone manage to get this or any other solution working?

Ideally the solution will enable me to still use create-react-app and not to use other packages but of course any solution would work.

1

There are 1 best solutions below

0
On

you can do it with your solution by add tsconfig.extends.json and use craco or any library to custom webpack. This is my craco.config.js:

const path = require('path')

module.exports = {
  webpack: {
    alias: {
      src: path.resolve(__dirname, './src/')
    }
  }
}