Solve src dir to import into React Native

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

When using webpack, it can be configured as this . With React Native packager, I have not found a way to do this.

+4
source share
2 answers

I did not find a solution that allows you to import exactly the way you want, but there are some tips on how to configure import locations in this stream .

My favorite decision

(Works in any JavaScript project, not just React Native, and allows you to write very short paths to link files.)

package.json src/ :

{
    "name": "src"
}

, : src. / , ( , package.json), :

import Foo from 'src/components/foo';


React Native :

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

MyApp - , index.ios.js index.android.js.

AppRegistry,

AppRegistry.registerComponent('MyApp', () => AppRootComponent);
+10

babel , . , babel-plugin-root-import node .babelrc,

"plugins": [
["babel-plugin-root-import", {
  "rootPathSuffix": "src"
}]
]

src,

import Component from '~/business/ComponentExample'
+2

Source: https://habr.com/ru/post/1666590/


All Articles