8

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!

chitzui
  • 3,778
  • 4
  • 28
  • 38

2 Answers2

2

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.

Community
  • 1
  • 1
Kaloyan Kosev
  • 12,483
  • 8
  • 59
  • 90
  • this will probably fail with server side rendering since the server does not go through webpack right? – chitzui Apr 23 '17 at 17:51
  • I don't have any experience with server-side rendering, but I assume there must be a way to do the same thing there. – Kaloyan Kosev Apr 23 '17 at 18:05
1

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"
Tom Nolan
  • 1,916
  • 4
  • 32
  • 51