Reputation: 1481
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.
Upvotes: 14
Views: 10011
Reputation: 2499
A good solution is to make your babel resolve all the logical paths before it transpile. You can accomplish this by adding babel-plugin-root-import to you're node dependencies and changing you're .babelrc, similar to the code bellow:
"plugins": [
["babel-plugin-root-import", {
"rootPathSuffix": "src"
}]
]
Now you can refer to all your components inside src like this
import Component from '~/business/ComponentExample'
Upvotes: 3
Reputation: 6509
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);
Upvotes: 29