Absolute imports issue in react with typescript

2.2k views Asked by At

I've been wandering through posts and posts about this and haven't been able to fix it. They all state pretty much the same: take notice of tsconfig.json's nesting, correctly set the baseUrl and explicitely mention filenames if were using index files. But I can't get my path aliases to work.

As I'm refactoring this project, this is getting necessary as the previous developer's dot-dot-dash hell is driving me crazy.

An excerpt from my project's structure:

.
+-- tsconfig.js
+-- package.json
+-- src
|   +-- ui
|   |   +-- hooks
|   |   |   +-- useProfessionalOnboarding
|   |   |   |   +-- index.tsx
|   |   +-- components
|   |   |   +-- professional
|   |   |   |   +-- onboarding
|   |   |   |   |   +-- availability
|   |   |   |   |   |   +-- ProOboardingServicesAvailability.tsx
|   |   +-- pages
|   |   |   +-- ProfessionalOnBoarding
|   |   |   |   +-- ...
|   |   +-- types
|   |   |   +-- ...
|   +-- index.tsx
|   +-- App.tsx

Now in ProOboardingServicesAvailability.tsx I'm trying to import the useProfessionalOnboarding hook as

import useProfessionalOnboarding from '@hooks/useProfessionalOnboarding/index';

My tsconfig.json being

{
  "compilerOptions": {

    "baseUrl": "src",
    "paths": {
      "@hooks/*": [
        "ui/hooks*"
      ],
    },

    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [ "src" ]
}

However I keep getting "Cannot find module or its correspondent type declarations".

I tried some other paths mappings as "@hooks/*": [ "./ui/hooks*" ], "@hooks/*": [ "src/ui/hooks*" ] "@hooks/*": [ "./src/ui/hooks*" ], none worked. Tried with and without the at-symbol, no difference.

There's a ton of work ahead and a small hideous chance of having to do the ant work of going through each file re-counting the '../'s. I crave for help. At least some way of tweaking or debugging.

btw I'm using Atom for text editor.

Error message screenshot

Thanks!

1

There are 1 answers

0
Vladimir On BEST ANSWER

I noticed that a message flashed between the run startup and the compiling step. I says compilerOptions.paths must not be set (aliased imports are not supported)! It was flashing fast and I had to take a screen capture to read it.

Looking up, I found this comment which states

create-react-app doesn't support path aliasing and probably won't for the near future.

I'll settle with baseUrl