A Cure for Relative Requires in React Native

Authors
Wojciech Szafraniec
Software Engineer
@
Callstack
No items found.

Say goodbye to require(‘../../../../`)

This is rather undocumented React Native feature so use with caution

When developing large React application, you usually want to split it into sub-projects so that you can share some logic between these targets (web, mobile) and keep your dependencies well organised.

It’s well known fact that `npm link` does not work with React Native yet, so almost everyone usually writes:

require(‘../../../core/todos/actions.js’)

Project structure

Supposing you have the following structure of your project:

/package.json (name = @acme/umbrella)
/src
 /core
   /package.json (name = @acme/core)
   /todos
 /mobile
   /package.json (react-native dependency, name = @acme/mobile)
   /config.js
   /containers
     /App.js

and you start packager from root of your project:

./src/mobile/node_modules/react-native/packager/packager.sh

you can reference all files from `core` or `mobile` folder by the package.json name.

That is — as long as there’s package.json inside a folder (it does not need to be inside node_modules), packager will make it accessible by its name.

Summary

So, to sum up, instead of writing:

// mobile/containers/App.js
const todos = require(‘../../../core/todos’);
const config = require(‘../config’);

you could just:

// mobile/containers/App.js
const todos = require(‘@acme/core/todos’);
const config = require(‘@acme/mobile/config’);

or even

const todos = require(‘@acme/umbrella/src/core/todos’);

but that’s rather ugly (though it shows that you can also reference by top-most package.json name either).

To make it working inside web target, use Webpack for instance and simply alias these folders.

How nice is that!

Note: Confirmed to work as of React Native 0.17
Table of contents
Need help with React or React Native projects?

We support teams building scalable apps with React and React Native.

Let’s chat
Link copied to clipboard!
//
Insights

Learn more about

React Native

Here's everything we published recently on this topic.

Sort
//
React Native

We can help you move
it forward!

At Callstack, we work with companies big and small, pushing React Native everyday.

React Native Performance Optimization

Improve React Native apps speed and efficiency through targeted performance enhancements.

Code Sharing

Implement effective code-sharing strategies across all platforms to accelerate shipping and reduce code duplication.

Mobile App Development

Launch on both Android and iOS with single codebase, keeping high-performance and platform-specific UX.

React Native Development

Hire expert React Native engineers to build, scale, or improve your app — from day one to production.