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.
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.
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.
(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';
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With