reactjstypescriptpathrelative-import

Can't resolve react path alias


Edit: I solved it, in the comments.

I'm trying to use alias for paths but I can't seem to get it to work I keep getting this error even though this path is correctly predicted by vs code.

This is a typescript-redux template I just created I'm trying to import the Counter.tsx in App.tsx

Compiled with problems:
ERROR in ./src/App.tsx 7:0-53
Module not found: Error: Can't resolve '$/features/counter/Counter' in '\frontend\src'

I added these to tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "$/*": ["*"] //Tried both @ and $ incase @ doesn't work
       //Tried the above and the below one with switching @ and $ everytime to make sure it's not the symbol
      "@/*": ["./*"] // I tried both @ and $ also 
    }
  },
  "include": ["src/**/*"]
}

frontend/src/features/counter/Counter.tsx => counter

    export function Counter() {
      return (
        <div>
        ...
        </div>
      );
    }

I tried to import as

import { Counter } from "@/features/counter/Counter";
import { Counter } from "$/features/counter/Counter";

and without the {}

this is the folder structure

frontend
├── node_modules
├── public
├── src
│   ├──App.tsx (where I'm importing the Counter) 
│   ├──app
│   ├──features
│   ├──├──counter
│   ├──├──├──Counter.tsx
├── tsconfig.json

I can't seem to get it to work at all


Solution

  • I managed to solve it by installing few packages not sure which worked but mainly craco which bypassed webpack settings I think anyways here goes the solution:

    1. Install these packages

       "@craco/craco": "^6.4.5",
       "@typescript-eslint/eslint-plugin": "^5.36.1",
       "@typescript-eslint/parser": "^5.36.1",
       "craco-alias": "^3.0.1",
       "eslint-import-resolver-alias": "^1.1.2",
       "eslint-import-resolver-typescript": "^3.5.0",
       "eslint-plugin-import": "^2.26.0",
      
    2. Create these files if you don't already have it

       craco.config.js
       tsconfig.paths.json
       tsconfig.json
      
    3. Add these to files

    tsconfig.json

        "compilerOptions":{//leave as is},
         "include": ["src"],
          "exclude": ["node_modules"],
          "extends": "./tsconfig.paths.json"
    

    tsconfig.paths.json

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

    craco.config.js

        const path = require("path");
        module.exports = {
          webpack: {
        
            alias: {
               "@Shared": path.join(path.resolve(__dirname, "./src/Modules/Shared")),
               "@Modules": path.join(path.resolve(__dirname, "./src/Modules")),
               "@": path.join(path.resolve(__dirname, "./")),
             },
          },
        };