React import from parent directory - javascript

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.

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

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

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/*"]
}
}
}

I looks fine to me . Did you tried with just
import Test from '../test';
instead of
import Test from '../test.js';
And also try without small bracket "( )";
I solved my issue with this. Hope it helps.

Related

Trying to edit "React Native init" file structure

I have been trying to get my head around React Native as I recently took the decision to switch to it from Cordova.
I have been trying to understand how container and component files should be properly structured inside src in order to correctly build.
To this end I have been attempting to run the initial index.android.js code out of a new file "app.js" which I have created in a folder I called js found in the original /src/main folder.
This is the index file code
/*Both index files index.ios.js and index.android.js MUST be indentical*/
var React= require('react-native');
var { AppRegistry } = React;
var App = require('./android/app/src/main/js/app.js')
AppRegistry.registerComponent('LearnD', () => LearnD);
And the app.js file can be found at this gist here.
I have been then receiving the following error:
Any help will be more than appreciated.
Thanks in advance,
Jake.
A typical setup for a React Native application looks something like:
└── YourApp
├── android # Native Android files, no .js here
├── index.android.js # Android entry point, must exist
├── index.ios.js # iOS entry point, must exist
├── ios # Native iOS files, no .js here
└── src # All your .js sources
├── components # All your .js sources
└── main.js # Your shared entry point
Your src/main.js can then export a single, shared entry point component for both platforms and uses other components inside the src/ directory:
// src/main.js
import React, { Component } from 'react';
import { View } from 'react-native';
import OtherComponent from './components/other-component.js'
// note export default
export default class Main extends Component {
render() {
return (
<View>
<OtherComponent />
</View>
);
}
}
And your index.ios.js and index.android.js components can import and register the main component as the application root component:
// index.ios.js and index.android.js
// both must exist, but they can be identical
import { AppRegistry } from 'react-native';
import Main from './src/main';
AppRegistry.registerComponent('YourApp', () => Main);
Within the src directory, you can then structure your app code in any way you best see fit, e.g. src/components and src/containers - entirely up to you!
Your file is trying to export App on line 48, which does not exist. You already have export default class LearnD on line 10, so omit line 48 and that should help

react compile error, Module not found

I got this error in my browser
Error in ./src/App.js
Module not found: ./components/todo in C:\Users\James\Desktop\react\src
This is what I got in my editor
import {TodoForm, TodoList} from './components/todo'
http://imgur.com/a/8YLod
I even tried import {TodoForm, TodoList} from './components/todo/' I wonder what's wrong.
Imports work on a per module basis for most loaders/bundlers. In other words, you'll need to import the form and list by doing the following:
import { TodoForm } from './components/todo/TodoForm'
import { TodoList } from './components/todo/TodoList'
As a side note, see https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export to make sure that you're exporting the components correctly. The curly braces around your import works for a named export as opposed to a default export.
In order to just import all files from the directory you must have an index.js file that exports everything from the directory
Which in your case the index.js file would look like this
Export * from 'TodoForm'
Export * from 'TodoList'
Note if the export statement doesn't work see this answer to fix the import / export statement
Do you think, when you wrote import {TodoForm, TodoList} from './components/todo', in TodoForm should be value than you exported from file TodoForm.js, and similarly with TodoList? It's don't works.
You should do import from some file. When you wrote from './components/todo' you tried doing import from todo directory. I guess, in egghead video that import works, because, they have index.js file in todo directory. And in this file they do export for every component separately. Try to add index.js file in todo directory with the following contents:
export * from './TodoForm.js';
export * from './TodoList.js';
it's will work.
So the thing is that when you do
import {TodoForm, TodoList} from './components/todo'
What happends is that your compiler will by default search the components TodoForm and TodoList from the index.js file since you have not mentioned explicitly which files to point to
So if in index.js you add something like
export * from './components/todo/TodoForm';
export * from './components/todo/TodoList';
Your approach will work.

React unable to import component -- module not found

I just started with React.js and I am unable to import component.
I have this structure as followed by this tutorial (YouTube link) :
-- src
----| index.html
----| app
------| index.js
------| components
--------| MyCompontent.js
This is my index.js:
import React from 'react';
import { render } from 'react-dom';
import { MyCompontent } from "./components/MyCompontent";
class App extends React.Component {
render() {
return (
<div>
<h1>Foo</h1>
<MyCompontent/>
</div>
);
}
}
render(<App />, window.document.getElementById('app'));
This is MyComponent.js:
import React from "react";
export class MyCompontent extends React.Component {
render(){
return(
<div>MyCompontent</div>
);
}
}
I am using this webpack file (GitHub link).
However, when I run this, my module fails to load.
I get this error in the browser console:
Error: Cannot find module "./components/MyCompontent"
[WDS] Hot Module Replacement enabled. bundle.js:631:11
[WDS] Errors while compiling. bundle.js:631:11
./src/app/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./components/MyCompontent in /home/kuno/code/react-hoteli/src/app
resolve file
/home/kuno/code/react-hoteli/src/app/components/MyCompontent doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.webpack.js doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.web.js doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.js doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.json doesn't exist
resolve directory
/home/kuno/code/react-hoteli/src/app/components/MyCompontent/package.json doesn't exist (directory description file)
/home/kuno/code/react-hoteli/src/app/components/MyCompontent doesn't exist (directory default file)
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.webpack.js]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.web.js]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.js]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.json]
# ./src/app/index.js 11:20-56 bundle.js:669:5
Can't figure out what went wrong here.
For anyone coming here without a typo, and is using Webpack, be sure to check for a clause like this:
resolve: {
extensions: [".jsx", ".js"]
},
in your webpack.config.js.
This tells your transpiler to resolve statements like:
import Setup from './components/Setup'
to
import Setup from './components/Setup.jsx'
This way you don't need the extension.
You have a typo in your import. You're requesting MyCompontent. Change to:
import MyComponent from "./components/MyComponent";
And all typos as well.
You can try to import MyCompontent from "./components/MyCompontent.js"
like this
import MyCompontent from "./components/MyCompontent.js";
You have written that the filename is MyComponent.js.
Thus, your import should look like
import { MyCompontent } from './components/MyComponent.js'
The problem for me was that import line was not generated correctly. I have this scenario:
--src
----elements
-----myCustomText.tsx
this is myCustomText.tsx file:
export interface Props {
text: string;
}
const MyCustomText = ({ text }: Props) => (
<Text>{text}</Text>
);
export default MyCustomText
And the generated import was this:
import MyCustomText from '../../elements/MyCustomText';
and I changed it to this:
import MyCustomText from '../../elements/myCustomText'
I don't know why the generated import line was generated automatically wrong.
I found myself here without a typo and without a webpack issue.
The solution for me was to restart the typescript server via VS Code.
I just had this issue, no type or webpack config issues.
What fixed it was changing the import from relative to the app root directory to relative to the file:
import MyComponent from "src/components/MyComponent";
to
import MyComponent from "../components/MyComponent";
If you're getting this from Visual Studio Code auto-importing via the shortest route, you can change it so it imports relatively. By going here:
menu File → Preferences → Settings → User Settings,
"typescript.preferences.importModuleSpecifier": "relative"
export 'Component' (imported as 'Component') was not found in 'react'
if you find your self stuck with this error simply go to mini-create-react-context, and go to cjs, and go to index.js and add "React" example: you will find this (Component) solution (React.Component) only if you extends to React.Component in you pages
Note: I have only used this on VS Code

Having issues with ES6 based multiple (React) Node.JS Module imports

I've been working on a React project and I'm having an issue trying to use ES6 to import several exported React node modules.
This is my code:
I should be able to include the AddFriendInput and FriendList from the hello folder without any issue. But I get this error when webpack/babel compiles:
ERROR in ./src/common/containers/Menu/indexRender.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../../hello in /Users/markpaul/Documents/projects/patient-portal-app/src/common/containers/Menu
# ./src/common/containers/Menu/indexRender.js 122:13-35
The content of my AddFriendInput.js file is like so:
import React, { Component, PropTypes } from 'react';
export default class AddFriendInput extends Component {
constructor(props, context) {
super(props, context);
this.state = {
name: this.props.name || ''
};
}
render() {
return (
<div>
</div>
);
}
}
I use webpack with babel to transpile my files. My Babel config is:
{
"presets": ["react", "es2015", "stage-1"]
}
The only way I can get it to work is to do this:
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';
But as you can see, this looks horrible.
Can someone please help.
Thanks in advance.
Create home/index.js
import AddFriendInput from './AddFriendInput'
import FriendList from './FriedList'
export { AddFriendInput, FriendList }
OLD ANSWER:
Rename AddFriendInput.js to index.js and after that you can import like this:
import AddFriendInput from '../../hello/AddFriendInput'
ES6 module doesn't automatically load nested directories/files
import by directory name (../../hello) implies that you have hello/index.js
updates
you could just create home/index.js as #Sergey mentioned or there is a module named auto-import that watch your directory and update index.js for you.
I think you are not understand the commonJS.
if the ../../hello is a folder, nodejs will find index.js file. so you must be have a file ../../hello/index.js.
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';
module.exports = {
AddFriendInput,
FriendList
};

Gulp throwing "is read-only while parsing file" error while running Gulp task

I'm trying to create ES6 module in JavaScript and I get error like: Line 20: "NotFound" is read-only while parsing file.
The NotFound is the name of my module.
'use strict';
import React from 'react';
const NotFound = React.createClass({
render: function () {
return (
<h1>Not Found!</h1>
);
}
});
export default NotFound;
I'm importing it the following way: import NotFound from './components/NotFound';
How to solve this issue? Changing file rights to 777 doesn't help at all (I know it's incorrect, but I was trying to find a solution).
Ok, it looks like I had defined a variable before calling import. The variable name was exactly the same as the imported module name. That was the root of the issue.

Categories