Understanding and maintaining a consistent order for import statements in React applications can greatly improve code readability and maintainability. Here’s a guideline on how to structure your import statements for clarity and efficiency.
This is not a programing style guide. It’s a guideline on how to organize your
imports.
Next, import assets like images, SVGs, and icons. Grouping these together helps in identifying resource dependencies at a glance.
Copy
// ** import iconsimport BackSvg from "@icons/BackSvg";import SearchSvg from "@icons/SearchSvg";// ** import assetsimport googleSvg from "@svg/google.svg";import AbsoluteLogo from "@svg/AbsoluteLogo.svg";import frontGirl from "@illustration/FrontGirl.svg";import userImage from "@illustration/userImage.webp";
Click on the following dropdown to view a sample index.js file with imports organized according to the order described above.
View Example of organized imports 👀
index.js
Copy
import React, { useEffect } from "react";import { useNavigate } from "react-router-dom";// ** import iconsimport BackSvg from "@icons/BackSvg";import SearchSvg from "@icons/SearchSvg";// ** import assetsimport googleSvg from "@svg/google.svg";import AbsoluteLogo from "@svg/AbsoluteLogo.svg";import frontGirl from "@illustration/FrontGirl.svg";import userImage from "@illustration/userImage.webp";// ** import third partyimport { toast } from "react-toastify";import { CircularProgress } from "@nextui-org/react";// ** import shared componentsimport Image from "@shared/Image";import Button from "@shared/Button";import Typography from "@shared/Typography";// ** import componentsimport AddFoodItem from "@components/AddFoodItem";import CalendarPopup from "@components/CalendarPopup";// ** import sub pages/sectionsimport Section1 from "./Section1";import Section2 from "./Section2";import Section3 from "./Section3";// ** import configimport env from "@src/config";// ** import state managerimport { useDispatch } from "react-redux";import { setLocale } from "@src/redux/slices/language";// ** import utilsimport { useStorableState } from "@utils/useStorable";// ** import hooksimport useStorable from "@src/utils/useStorable";// ** import apisimport { getUserProfileApi } from "@api/auth";import { confirmOrderApi } from "@api/cart";
Import aliases simplify import statements, making them more readable and manageable, especially in large projects. Here’s how to use them effectively in Node.js, React, and Next.js 14.
React/Next.js: Configure jsconfig.json or tsconfig.json for alias paths.
Node.js: Use module-alias package or configure package.json for custom paths.
Import aliases streamline project structure by reducing the complexity of import statements, enhancing code readability and maintainability.References:
By following this order, your imports will be neatly organized and easily understandable to anyone reading your code. This not only aids in development but also in maintaining the codebase efficiently.