chitzui
chitzui

Reputation: 4098

how to handle the import hell in react?

I’m running my react app via Node. Is there a way to easily handle this import hell?

I’m running

./node_modules/.bin/babel-node --presets react,es2015 server/server.js

as npm start. And server.js is a simple Express Server that serves a ReactDOMServer.renderToString(<MyApp />)

Some of my react components have something like this:

import GenericTemplate from "../../templates/GenericTemplate/GenericTemplate";
import Footer from "../../organisms/Footer/Footer";
import Header from "../../organisms/Header/Header";
import Hero from "../../organisms/Hero/Hero";
import MainMenu from "../../organisms/MainMenu/MainMenu";
import TodoList from "../../organisms/TodoList/TodoList";

this is prone to error, one changement like directory name would result in manually entering every file to update this.

do you have any idea how I can fix this. Ideally I would have something like this:

import { Footer, Header, Hero, MainMenu, TodoList } from "myComponents"

is that possible? How?

Thank you!

Upvotes: 9

Views: 2353

Answers (2)

Kaloyan Kosev
Kaloyan Kosev

Reputation: 13067

This also doesn't look a lot better to me:

import { Footer, Header, Hero, MainMenu, TodoList } from "myComponents"

... because in order to do that, you need to export / import to "myComponents" every time you create a new component.

The core issue I see in your example is that using relative paths for imports makes your code base very hard to maintain.

To escape the "import hell" in React, one popular option is to make the import statements without relative paths.

With a minor tweak to your Webpack configuration, you can get it to load files relative to the app root. See here and read more here.

Upvotes: 2

Tom Nolan
Tom Nolan

Reputation: 1957

You can create a common components file in your organisms directory to achieve that. Just create a new common.js or whatever name with the following:

export Footer from "./Footer/Footer";
export Header from "./Header/Header";  
export Hero from "./Hero/Hero";
export MainMenu from "./MainMenu/MainMenu";
export TodoList from "./TodoList/TodoList";

Then in your other file:

import { Footer, Header, Hero, MainMenu, TodoList } from "path to common.js"

Upvotes: 1

Related Questions