How to Use Absolute Paths in React Native

David Woody
2 min readAug 5, 2016

--

TL;DR — 1) Add a package.json file with { “name”: “FOLDER_NAME” } in it to the folder you’d like to import from. 2) import Thing from ‘FOLDER_NAME/thing’.

Relative paths are cool…

import Thing from ‘./thing’;

…except when going “up” in the folder structure.

import Blah from ‘../../../../../blah’;

I know, it’s hard to look at…

On a positive note, two reasons I like using absolute import paths:

  1. It’s easier to quickly understand where the import is coming from, and
  2. It’s optimized for copy/paste workflow

Honorable mention: if you restructure things down the road, it’s also easier to find/replace absolute paths.

In your React Native project, chances are you keep your code in a single folder, such as “app”. If you have a directory named “app” this is what an absolute path might look like:

import Thing from ‘AwesomeApp/app/some/thing’

What sucks about this is literally all import statements (or require calls, if you’re still into that) would start with “AwesomeApp/app/”, which is a lot to ask, when the alternative is simple to add a series of “../” (the key strokes are just so close together, it’s too easy).

To alleviate this pain point, you can simply add a package.json file inside the folder from where you want to import. In this case since all our code is under the “app” folder, we’d put the file here:

AwesomeApp/app/package.json

Then, add a “name” property to the json file with the folder name as its value (you can call it whatever you’d like, but really, that’ll just confuse people, including you in 6 months). The shorter, the better.

{ “name”: “app” }

Now, you can import using that name as a reference.

import Thing from ‘app/some/thing’

I originally found this tip pointed out here. Hopefully writing about it specifically will make it easier for others to find, and make your absolute importing experience just a little brighter.

Note: For a nearly identical experience without the need for adding a package.json file, this babel plugin can work wonders.

--

--

David Woody

Partner at Differential. JavaScript Developer. Certified Public Accountant. Formal Education in Finance, Economics, and Accounting. Mini-writing: @davidjwoody