Shashika Virajh
Shashika Virajh

Reputation: 9457

How to set paths properly in react-native

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

Answers (3)

Stanislav Mayorov
Stanislav Mayorov

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

Mike M
Mike M

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

deathangel908
deathangel908

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

Related Questions