How to use tsconfig path aliases in a frontend React project

38 views Asked by At

I want to setup the paths config in my create-react-app React frontend project mylib.

Here is my tsconfig.json:

{
  "compilerOptions": {
    ...
    "baseUrl": "src",
    "paths": {
      "@bla/*": ["./*"]
    }
  },
  "include": [
    "src"
  ]
}

Here's how my project's folders look:

mylib
-build
-src
--stuff
---things
----x.js

This project is a custom library that I compile using Babel, and that I npm link to test it in another React project, myproject. Here's the top of the myFile.tsx file in myproject:

import * as myImport from '@bla/stuff/things/x'

Here's the output:

Failed to compile. ../myproject/build/stuff/things/myFile.js Module not found: Can't resolve '@bla/stuff/things/x' in 'C:\Users\xxx\myproject\build\folderInWhichMyFileIs'

What am I missing here?

I have found other related SO questions, but people are saying to use the module-alias library, which only works for backend code. I'm also not using ts-node.

1

There are 1 answers

4
Elias Salom On

You'll typically set up path aliases to simplify imports. This can make your project's directory structure cleaner and easier to manage.

the tsconfig must be in the project root, and then you can use the folder structure like this, if the folder has subfolder you need to include it

// This does't work ❌
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
  },
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
  "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
    }
}
// This should work ✅
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
    "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
    }
  },
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
}