Search code examples
reactjstypescriptpathabsolute

Create React App Typescript Absolute Paths Not Working


I tried to create a new typescript React app using the command:

npx create-react-app config-app --template typescript

Then, under the src directory I created some folders/files so that it looked like the following:

-config-app
  -src
    -types
      -maybe.ts
      -nullish.ts
    -utils
      -nullish.ts

Both the maybe.ts and nullish.ts files contain an export type operation.

In the nullish.ts app it has the following import:

 import type { Maybe, Nullish } from 'types'

I am getting the error Cannot find module 'types' or its corresponding type declarations. So it seems absolute paths are not working. I have followed the suggestions on this site to add the "baseUrl": "src" and "include": [ "src" ] into the tsconfig.json file. I have an older react typescript app for which this was working but it doesn't with this latest template.


Solution

  • You should add a index file next to nullish.ts and maybe.ts and export the types of these files in the index file as follows:

    Structure:

    -config-app
      -src
        -types
          -maybe.ts
          -nullish.ts
          -index.ts
        -utils
          -nullish.ts
    

    index.ts content:

    export * from './maybe'
    export * from './nullish'
    

    at last you can import types without error as follows:

    import  type  {Maybe, Nullish} from 'types'