8

Bear with me, I'm not sure if this is purely a React Native issue, or just an ES6 question in general. But I noticed I'm unable to do this:

import {navBarRouteMapper} from '/src/helpers';

I get an error saying it's unable to resolve the module. I have to do this instead:

import {navBarRouteMapper} from '../../../src/helpers';

Keeping track of folder depth can get a bit unmanageable as the complexity of the app grows. Why am I not able to use an absolute path?

EDIT:

I see people are recommending adding babel, but I don't want to pollute React Native's system. There's obviously transpilation to ES6 already going on. I was hoping for a solution specific to the React Native ecosystem.

balajeerc
  • 3,998
  • 7
  • 35
  • 51
ffxsam
  • 26,428
  • 32
  • 94
  • 144
  • 1
    Possible duplicate of [Importing node modules from root directory using es6 and babel-node](http://stackoverflow.com/questions/31068698/importing-node-modules-from-root-directory-using-es6-and-babel-node). React Native uses Babel so I believe your answer lies here. – Mike Cluck Jan 25 '16 at 20:30
  • You can do this with Browserify. – elclanrs Jan 25 '16 at 20:30
  • do note that the path is a string, and need not be hard-coded in each place it's used. you can use the run time importing too. – dandavis Jan 25 '16 at 20:32
  • This doesn't really have anything to do with ES6, since module loading is not part of ES6. – Felix Kling Jan 26 '16 at 01:40
  • You are missing the module name in your require, check this answer http://stackoverflow.com/a/35819147/580167 – wdev Jun 30 '16 at 14:44

1 Answers1

4

There is actually a pretty clean solution for React Native, have a look here: https://medium.com/@davidjwoody/how-to-use-absolute-paths-in-react-native-6b06ae3f65d1#.u47sl3p8x.

TL;DR:

You'll just have to create a package.json file in your src/helpers folder:

{
   "name": "@helpers" 
}

And you will be able to import it from anywhere:

import { navBarRouteMapper } from '@helpers'
Charles Mangwa
  • 183
  • 2
  • 6