Configuring Absolute Imports in React and React Native with Typescript
There are two great reasons to move to absolute imports. One is to avoid long relative paths, and the other is to make sure imports don’t break when moving stuff around. Read more about it here.
As before, we will explore the simplest ways to configure this for our apps.
React Native
We will do this in two stages.
STEP 1
First, let's tackle this for the packager. We do this by using a babel plugin called babel-plugin-module-resolver.
yarn add -D babel-plugin-module-resolver
And we configure this in our babel.config.js
by adding a new plugins
key and specifying our alias there
module.exports = {
presets: ['module:metro-react-native-babel-preset'], // existing
// add the following
plugins: [
[
'module-resolver',
{
root: ['.'],
alias: {
'@src': './src',
},
},
],
],
};
Here we have configured only one universal alias, but this can theoretically have custom root directories and multiple aliases. See example here
STEP 2
Now we have to make sure that the typescript engine built into VSCode also recognizes this, and does not show red squigglies!
For this, we will configure the same alias in our tsconfig.json
. There are two properties of interest to us there, both of which are commented out in the default file. These are baseUrl
and paths
. This is what we want them to look like (similar to the babel config):
"baseUrl": ".",
"paths": {
"@src/*": ["src/*"],
},
And that’s it. Now you can use absolute import WITH aliases in React Native. For example,
// this
import { PermissionsPage } from './views/PermissionsPage';
// now becomes
import { PermissionsPage } from '@src/views/PermissionsPage';
React
React does not allow us to use aliases (unless we really customize the packager config). But we can still use absolute imports (which is 90% of what we want, anyway)
The configuration is very easy. We just have to add ONE little bit to our tsconfig.json
In the compilerOptions
, we add one line
{
"compilerOptions": {
// existing stuff
"baseUrl": "./" // add this line
},
"include": ["src"] // existing
}
And now we can start referencing everything as absolute paths. For example,
// this
import { PermissionsPage } from './views/PermissionsPage';
// now becomes
import { PermissionsPage } from 'src/views/PermissionsPage';
The only difference is that there is no aliasing.