Absolute Paths for Create-React-Native-App Expo TypeScript

Enrico Valbuena
VAL PUNK
Published in
2 min readAug 15, 2018
“Wooden boardwalk with rope fence through the grass field after the sunset” by Senor Sosa on Unsplash

It took me a minute to figure out how to get absolute paths working in a CRNA project with TypeScript. The context of this article is a Create React Native App, and as such it comes with the below folder structure. If you have a different setup and just want to see the solution, skip to Solution.

Context: Create React Native App (with TypeScript)

/node_modules
App.test.tsx
App.tsx
app.json
package.json
tsconfig.json

Because CRNA’s package.json has "main" as:

{
...
"main": "./node_modules/react-native-scripts-ts/build/bin/crna-entry.js",
...
}

We are not able to move our App.tsx file around. (If you want to change that, check out this comment on github). So likely, you left it where it was and went on your merry way with something like this:

/node_modules
/src
/components
/compositions
| Text.tsx
| TextInput.tsx
| index.tsx
/templates
| TextInputWithLabel.tsx
| index.tsx
/pages
/Login
| Login.tsx
/Signup
| Signup.tsx
| index.tsx
App.test.tsx
App.tsx
app.json
package.json
tsconfig.json

And as you were developing your Login.tsx file, you wanted to use TextInputWithLabel.tsx, so you import it with:

import { TextInputWithLabel } from "../../components/templates"

While this isn’t horrible, you’ve been around the block enough to know eventually, in some other file deep down in your folder structure, you can end up trying to get your TextInputWithLabel.tsx with something like

import { TextInputWithLabel } from "../../../../../components/templates"// Yikes 😬

Solution

VS Code allows us to modify a tsconfig.json file to allow us to fix this issue. We can add something like this to it:

{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"components/*": ["./components/*"]
},
...
}

While this fixes our linting errors, the app will throw errors when trying to compile. We can follow the instructions here to fix that. In the./src/components I added a package.json file with the below content:

{
"name": "components"
}

I can now reference this folder absolutely from anywhere in the project with:

import { TextInputWithLabel } from "components/templates"

Voila!

Hopefully this got it working for you.

Debuggin Some Errors:

If you’re having trouble getting this to work, you may want to try deleting your /node_modules folder as well as your yarn-lock.json or package-lock.json files and running yarn or npm install depending on which package manager you use.

--

--