Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 521
chitzui Avatar asked Apr 23 '17 14:04

chitzui


1 Answers

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.

like image 193
Kaloyan Kosev Avatar answered Oct 02 '22 10:10

Kaloyan Kosev