Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native import files outside of main directory

I am trying to make a demo app for some components using Expo and react-native. (Or I also could use regular React-Native)

My problem is I cannot import files outside of the demo app

Here is the structure I have
|-- Components/ | |-- libs | |-- node_modules | |-- index.js | |-- package.json | |-- demo/ | | |-- node_modules | | |-- App.js | | |-- package.json

Inside of demo/App.js, I am trying to import one of my components from the upper directory but with no luck. All the components are exported in ./index.js

Inside of App.js, I tried : import {MyComponent} from 'Components', import {MyComponent} from '../index', or import {MyComponent} from '../../Components/' but none seem to work.

I got the following type of error Directory /Users/kevin/web/myprojects/Components/index doesn't exist

What Am I doing wrong ?

like image 546
Kevin Amiranoff Avatar asked Apr 03 '17 09:04

Kevin Amiranoff


2 Answers

You could turn the root folder into a local npm package...

  1. In the root folder, open package.json
  2. Set the name field in package.json
  3. Run npm pack.
  4. Copy the gz tarball name given at the end of the terminal.
  5. Open the directory of your App.js
  6. Run npm install ../NAME_OF_TARBALL_THAT_YOU_COPIED
  7. In the file, do import {MyComponent} from 'NAME_IN_PACKAGE.JSON'
like image 109
Fernando Rojo Avatar answered Oct 07 '22 01:10

Fernando Rojo


The way the react-native packager works right now, it's just going to scan the roots of your project and below when creating the JavaScript bundle, so it will be really hard to do this.

You basically just need to put the files under the root of your directory. There are some tools out there for syncing files from another directory into a directory under the root so you could use one of those if you really need to.

Some people are working on ways to make symlinks work with this. Notably, you might look at Haul from Callstack. https://github.com/callstack-io/haul But that isn't integrated into Expo yet.

like image 38
theram Avatar answered Oct 07 '22 00:10

theram