Skip to main content

Path alias (optional)

Before we move on to the next bit, let's also set up a TypeScript path alias. A path alias allows importing modules with custom aliases instead of relative paths.

There's two main benefits for this:

  1. we don't have to manage the long ../../ train when importing files from deeply nested directories
  2. we don't have to update these paths when moving files

As an example just see how much cleaner this will looks:

Before:

import theme from "../../../../../theme";

After:

import theme from "@/theme";

Add the alias

You could set up aliases to specific directories or folders, but in this case let's keep things simple and add a single @/ alias to the root of the project. This means that by starting the import with @/ you can type the path as if from the root of your project folder:

Update: tsconfig.json
@@ -1,6 +1,11 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
- "strict": true
+ "strict": true,
+ "paths": {
+ "@/*": [
+ "./*"
+ ]
+ }
}
}

Update existing files to use the alias

After making these changes, close and reopen your editor and restart the metro bundler.

Update: app/_layout.tsx
@@ -1,7 +1,7 @@
import { Tabs } from "expo-router";
import Entypo from "@expo/vector-icons/Entypo";
import Feather from "@expo/vector-icons/Feather";
-import { theme } from "../theme";
+import { theme } from "@/theme";

export default function Layout() {
return (
Update: app/index.tsx
@@ -1,6 +1,6 @@
import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View } from "react-native";
-import { theme } from "../theme";
+import { theme } from "@/theme";

export default function App() {
return (
Update: app/profile.tsx
@@ -1,5 +1,5 @@
import { Text, View, StyleSheet } from "react-native";
-import { theme } from "../theme";
+import { theme } from "@/theme";

export default function ProfileScreen() {
return (
Default template

This path alias is already set up in the default template. We're setting this up manually because we started with the blank template.

Checkpoint