← Back
create-react-app react typescript

Using absolute paths with Create React App

TL;DR: I've recently discovered that you can use absolute paths in a Typescript Create React App project.

Absolute paths means that instead of using something like this:

import MyComponent from '../../devices/DeviceItem'
import { useDevices } from '../../../hooks/useDevices'

We write this (that is much more readable IMO):

import MyComponent from 'components/devices/DeviceItem'
import { useDevices } from 'hooks/useDevices'

Basically we need to tell Typescript that the folders inside "src/" can be treated as "absolute".

How? Adding this line to tsconfig.json 👇

{
"compilerOptions": {
"baseUrl": "src" 👈
...
}

We also need to notify eslint and vscode by adding those lines to package.json:

  "eslintConfig": {
...
"settings": {
"import/resolver": {
"node": {
"moduleDirectory": [
"node_modules",
"src/"
]
}
}
},