I’m using TypeScript and was looking for way to import using absolute path. The solution in this forum did not work for me but I could not comment there as the topic was locked. I found a solution somewhere else and would like to share it.
I put all my components in the app/ folder. Below is the structure.
...
app/
|-- package.json
|...
App.tsx
tsconfig.json
babel.config.js
...
I need to add package.json file in app/ folder.
{
"name": "app"
}
I modified tsconfig.json. Add baseUrl and paths
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"app/*": ["./app/*"]
},
...
}
}
babel.config.js
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
{
alias: {
app: './app',
},
},
],
],
};
};
Now I can
import SomeComponent from 'app/subfolder/SomeComponent'
<Image
source={require('app/assets/images/home.jpg')}
resizeMode="cover"
/>
Hope it helps.
1 Like
Wanted to share my config that follows the same absolute path syntax as NextJS, allowing for something like… @/components/StyledText.tsx
tsconfig.json
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"jsx": "react-native",
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"],
"@/ui/*": ["ui/*"],
"@/util/*": ["util/*"],
"@/screens/*": ["screens/*"],
"@/navigation/*": ["navigation/*"],
"@/constants/*": ["constants/*"],
"@/assets/*": ["assets/*"],
"@/hooks/*": ["hooks/*"],
}
}
}
babel.config.js
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
"react-native-reanimated/plugin",
[
require.resolve("babel-plugin-module-resolver"),
{
root: ".",
alias: {
"@/components": "./components",
"@/ui": "./ui",
"@/util": "./util",
"@/screens": "./screens",
"@/navigation": "./navigation",
"@/constants": "./constants",
"@/assets": "./assets",
"@/hooks": "./hooks",
},
},
],
],
};
};
Usage
...
import Colors from "@/constants/Colors";
import { MonoText } from "@/components/StyledText";
import { Text, View } from "@/components/Themed";
1 Like
Don’t forget to reset the cache after setting new aliases. Just run react-native start --resetCache
.
Reference