Stop using relative paths in your React Native imports. Use Aliases instead.
Andres Urdaneta
Posted on June 6, 2021
Use Aliases in your imports with Babel
Instead of doing this in your imports i.e:
import Component from '../../../components/shared/Header';
You could do something like this from anywhere in your project i.e:
import Component from 'components/shared/Header';
Or you could even go as deep as you want i.e:
import Component from '@/shared/Header';
You get the point... no more relative paths ('../../../../../../'
) to import any of your components.
How?
- Install required dependencies
npm i babel-plugin-module-resolver metro-react-native-babel-preset
Head over to your
babel.config.js
file in your project root directory. (If it doesn't exist, create it)Add the
module-resolver
plugin to your plugins array like this:
module.exports = {
presets: ['module:metro-react-native-babel-preset']
plugins: [
[
'module-resolver',
{
root: ['.'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'@': './src/components',
'constants': './src/constants',
'##': './src/examples',
},
},
]
]
};
Make sure to provide the path you want to reference with an alias, and the alias name itself.
According to the example above now you're able to import files or modules like this
import MyComponent from '@/MyComponent.js'
import MyConstantFile from 'constants/myConstant.js'
import MyExample from '##/MyExample.js'
I would love to engage with other developers like you. Get in touch on Twitter! @dev_astador
Posted on June 6, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
June 6, 2021