Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use absolute paths for import?

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.

like image 329
ffxsam Avatar asked Jan 25 '16 20:01

ffxsam


People also ask

How do you use absolute imports react?

Absolute import in React Typescript json file inside project root directory. Just open it and add the same baseUrl setting as Javascript. Happy Learning!

How do you specify an absolute path?

An absolute path is defined as the specifying the location of a file or directory from the root directory(/). In other words we can say absolute path is a complete path from start of actual filesystem from / directory.

Why is it better to use relative paths instead of absolute paths?

Relative links show the path to the file or refer to the file itself. A relative URL is useful within a site to transfer a user from point to point within the same domain. Absolute links are good when you want to send the user to a page that is outside of your server.

How do you use absolute path in Python?

An absolute path is also known as the full path and starts with / in Linux and macOS and C:/ on Windows. To find an absolute path in Python you import the os module then you can find the current working directory using os. path. abspath("insert-file-name-here") in your Python script.


1 Answers

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'
like image 103
Charles Mangwa Avatar answered Sep 23 '22 22:09

Charles Mangwa