Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS import component outside src/ directory

I have two react apps(A-app, B-app). I need to import one component from A-app to B-app. But when I tried to do this I have seen this error.

./src/App.js
Module not found: You attempted to import ../../src/components/Dashboard/container which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

I tried to do symlink on this component in B-app node_modules. But it didn`t work.

Also I tried to create .env file in root project directory and put this NODE_PATH=src/ in file. But this solve doesn`t work too.

How can I fix this?

Sorry for my English.

like image 676
Just Snake Avatar asked Apr 07 '18 07:04

Just Snake


People also ask

How do I import a module outside SRC React?

To import a component from another file in React: Export the component from file A , e.g. export function Button() {} . Import the component in file B as import {Button} from './another-file' . Use the imported component in file B .

What is import {} In React?

Since we have a default export, importing anything from that file will provide us with a person object. For imports from the info. js file, we will import from two different constants. Therefore, we use {} to precisely target specific things from that file.

How do I import dynamic components?

In React, dynamically importing a component is easy—you invoke React. lazy with the standard dynamic import syntax and specify a fallback UI. When the component renders for the first time, React will load that module and swap it in.


2 Answers

I stumbled on this post while trying to solve a similar issue. I think the solution might be relevant so I'm posting it here.

As of NPM 2.0 you can declare local dependencies in package.json. This allows you to maintain local modules in a folder outside of src/ and have them copied to node_modules during npm install.

Place your module anywhere outside of src/, for example:

./packages/app-b-dashboard

Declare a local dependency in package.json using the file: prefix:

"dependencies": {
  "app-b-dashboard": "file:./packages/app-b-dashboard"
}

Run

npm install

Now you can import it in your A-app

import Dashboard from 'app-b-dashboard/container' 
like image 143
olipo186 Avatar answered Oct 26 '22 12:10

olipo186


Got to your A-app node_modules folder and run the following

ln -s ../../../src/components/Dashboard ./app-b-dashboard

After creating the following symbolic link in your node_modules folder you can import in you A-app

import Dashboard from 'app-b-dashboard/container'

The names might be different depending on the specific layout of your project. This is my best guess based on the info you provided.

like image 27
Moti Korets Avatar answered Oct 26 '22 12:10

Moti Korets