When we develop an application with many folders the import paths are often too large and this affects the readability of your code as per the example below:
import Input from '../../../src/components/Input';
import HomeSvg from '../../../src/assets/home.svg';
To solve this problem we will have to make some settings:
1ยบ Step: Libs Install
- Install metro-react-native-babel-preset and babel-plugin-module-resolver as devDependencies
npm install metro-react-native-babel-preset --save-dev
yarn add metro-react-native-babel-preset -D
npm install babel-plugin-module-resolver --save-dev
yarn add babel-plugin-module-resolver -D
2ยบ Step: Babel Configuration
alias: In will have the paths and the name that will be used when calling the specified path.
extensions: Extensions to the files that will be used
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo', 'module:metro-react-native-babel-preset'],
plugins: [
"module-resolver",
{
alias: {
// This needs to be mirroned in tsconfig.json/jsconfig.json
components: "./src/components",
svg: "./src/assets",
},
extensions: ['.js', '.jsx', '.tsx'],
},
],
};
};
3ยบ Step: tsconfig/jsconfig configuration
Access the tsconfig.json or jsconfig.json file
If neither of these files exist, create them in the project root
paths: Add the same paths added in babel.config.js, if the called folder does not have an index calling all files it is necessary to put "/*"
baseUrl: Tell the typescript where to start importing
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
// This needs to be mirrored in babel.config.js
"components": ["./src/components"],
"svg/*": ["src/assets/*"],
}
},
"extends": "expo/tsconfig.base"
}
Final Result
import Input from 'components/Input';
import HomeSvg from 'svg/home.svg';
Top comments (0)