Reputation: 9457
In my React-Native application, import paths are like this.
import {
ScreenContainer,
SLButton,
SLTextInput,
} from '../../../../../components';
import { KeyBoardTypes } from '../../../../../enums';
import { SIGN_UP_FORM } from '../../../../constants/forms';
I have seen some applications, there the paths are more clear and elegant without '../../../'s. How can I achieve this in React-Native??
I saw in my solution that, in every folder there was a package.json file. I'm not sure if that is the proper way to do it.
Upvotes: 1
Views: 3612
Reputation: 4452
It's possible. I've done it, but I don't recommend it. It doesn't work when xcode starts bundler because you have to do npm start -- --reset-cache
. You have to use workarounds to learn your IDE understand this paths. It doesn't work with Flow.
You can use npm babel-plugin-module-resolver
. Babel is used by metro budler.
.babelrc
.
{
"presets": ["react-native"],
"plugins": [
[
"module-resolver",
{
"root": ["./src"],
"alias": {
"src": "./src",
"root": "./"
}
}
]
],
}
Upvotes: 0
Reputation: 4436
Starting around React Native version 0.55 (I'm not sure exactly when this was enabled) you can just use your project name as the path root.
import {DatePanel} from 'MyProject/components/panels';
import HomeScreen from 'MyProject/screens/HomeScreen';
No problems with flow, Xcode, etc.
Upvotes: 1
Reputation: 9699
You need to configure alias in webpack.config.js. You can find an example here and here
webpack.config.js:
alias: {
'@': path.join(__dirname, 'src')
}
your.js.file.js
import '@/utils/classComponentHooks';
if you don't use wepback for react-native (despite you can). You can also try .babelrc
[
'module-resolver',
{
root: ['./src'],
alias: {
'@': './src',
},
},
];
Upvotes: 1