Skip to content

Instantly share code, notes, and snippets.

@jerray
Last active April 22, 2023 04:47
Show Gist options
  • Save jerray/6f003d0f0d3c6019912db32114a21d67 to your computer and use it in GitHub Desktop.
Save jerray/6f003d0f0d3c6019912db32114a21d67 to your computer and use it in GitHub Desktop.
Use the @ alias to refer to your project root in Expo (React Native)

Use the @ alias to refer to your project root in Expo (React Native)

I spent some time and finally figured out the solution.

Note the difference between the paths in the tsconfig.json file and the alias in the babel.config.js file. The module resolver automatically adds a slash after the @ character, then uses it to generate a regular expression /^@(\/.*|)$/ to match the import path.

So if we add a slash after @ in the alias (@/), the module resolver can't match (using /^@\/(\/.*|)$/) the import path.

For example, if we have the following directory structure:

project_root/
├── app/
│   ├── _layout.tsx
│   ├── index.tsx
│   ├── posts/
│   │   └── [id].txt
│   └── settings/
│       ├── tab1.tsx
│       └── tab2.tsx
└── components/
    └── ui/
        └── Text.tsx

Using the following configuration, we can change the code from

import Text from '../../../../components/ui/Text';

to

import Text from '@/components/ui/Text';

And make sure the babel plugin babel-plugin-module-resolver is installed.

module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
root: ['.'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'@': '.',
},
},
],
require.resolve('expo-router/babel'),
],
};
};
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"paths": {
"@/*": ["./*"]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment