Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React import from parent directory

I am unable to import file from parent of project directory. To make things as simple as possible, I created new react-native project and file 'test.js' in a parent directory. I tried to import it with this code:

var Test = require('../test.js');

and

import Test from ('../test.js');

None of these worked - when run in xcode I have following error:

uncaught error Error: UnableToResolveError: Unable to resolve module ../test.js from /Users/UserName/Downloads/TestReact/index.ios.js: Invalid directory /Users/UserName/Downloads/test.js

Is it possible to import file from parent directory with react-native? I̶ ̶k̶n̶o̶w̶ ̶i̶t̶ ̶w̶o̶r̶k̶s̶ ̶w̶i̶t̶h̶ ̶r̶e̶a̶c̶t̶J̶S̶.

Regards

edit - adding code

test.js

'use strict';

import React, {Component,View,Text} from 'react-native';

  class Test extends Component{
  render(){
    return (
    <View>
      <Text>
        SAMPLE TEXT
      </Text>
    </View>
    );
  }
}
module.exports = Test;

index.ios.js

'use strict';
import React, {AppRegistry, View} from 'react-native';
import Test from '../test.js';

var TestReact = React.createClass({
  render: function() {
    return (
      <View><Test/></View>
    );
  }
});

AppRegistry.registerComponent('TestReact', () => TestReact);

edit - added files hierarchy: screenshot

edit - actually I was wrong, it's impossible with web react too. When I try to build I got following error:

Module parse failed: /path_to_file/aaa1.js Line 1: Unexpected token You may need an appropriate loader to handle this file type.

So adding react tag to the question.

like image 753
Maciej S Avatar asked Nov 26 '15 11:11

Maciej S


3 Answers

Try this ./../Component.js. It works for me. More over if you need access a component from adjacent directory ./../AdjDir/Component.js

like image 105
Alexey Nikonov Avatar answered Oct 12 '22 04:10

Alexey Nikonov


This problem may be because react only allows you to import from the src folder. So all resources have to placed in this directory.

Also when you go more than two parent directories back you need to use this syntax: ../../../myfolder/myFile.js going back 2 parent directories

like image 31
Ruben Rick Avatar answered Oct 12 '22 05:10

Ruben Rick


finally a stack overflow question I can answer:

Simply add below jsconfig.json to the base route of your react folder. (Assuming you put all of your react code in "src" folder)

example_react_app
  ---> public
  ---> src
  ---> jsconfig.json

jsconfig.json file content

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "*": ["src/*"]
    }
  }
}
like image 4
stanley_manley Avatar answered Oct 12 '22 04:10

stanley_manley