Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve src dir for imports in React Native

Tags:

react-native

How can I configure React Native to import files relative to the src directory? In other words, I want to write import Foo from 'components/foo' rather than import Foo from '../../components/foo'.

When using webpack it can be configured like this. With React Native packager I haven't found a way to do this.

like image 771
henkimon Avatar asked Jan 12 '17 10:01

henkimon


People also ask

Why import is not working in react native?

Import errorYou likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of 'App'. The React Native team has made this error more descriptive since the last version. Usually, mixed-up default and named imports are the culprits.


1 Answers

I haven't found a solution that let's you import exactly the way you want, but there are several suggestions of how to configure import locations in this thread.

My favorite solution

(Works in any JavaScript project, not just React Native, and let's you write very short paths to reference files.)

Create a package.json in your src/ directory with the contents:

{
    "name": "src"
}

What this does is say: This folder is a package, named src. Then you can import any file/directory inside that package by simply adding it's position (relative to the directory the package.json is in) after the name of the package:

import Foo from 'src/components/foo';


Another solution

In any React Native Project, you can do:

import Foo from 'MyApp/src/components/foo';

where MyApp is whatever name you registered in your index.ios.js and index.android.js files.

The app name is registered using one of the AppRegistry methods, such as

AppRegistry.registerComponent('MyApp', () => AppRootComponent);
like image 87
ArneHugo Avatar answered Dec 21 '22 08:12

ArneHugo