In order to avoid \'../../../../\' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instea
Summary:
The npm package babel-plugin-module-resolver
is needed, as well as some configuration in tsconfig.json
and babel.config.js
Step by step:
npm install babel-plugin-module-resolver
(or yarn add babel-plugin-module-resolver
)
tsconfig.json
: Add "baseUrl": "."
to compilerOptions
babel.config.js
: Add a key named plugins
with the following value:
[
[
'module-resolver',
{
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx',
'.android.js',
'.android.tsx',
'.ios.js',
'.ios.tsx'
],
root: ['.']
}
]
]
Complete configuration:
tsconfig.json
:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"baseUrl": "."
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}
babel.config.js
:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx',
'.android.js',
'.android.tsx',
'.ios.js',
'.ios.tsx'
],
root: ['.']
}
]
]
};
This is for a clean new project created using npx react-native init MyTestApp --template typescript
on React Native version 0.60.5