Search code examples
reactjslazy-loading

Lazy loading named import throwing error "exporting error"


I'm trying to implement lazy loading, components are being exported from a single file named "index.js" I'm getting an error "component not exported" but I'm importing and importing all the components.

Demo: Stackblitz

I'm importing the files as follows:

import React, { lazy, Suspense } from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Layout from './components/Layout.jsx';
import {
  Route,
  RouterProvider,
  createBrowserRouter,
  createRoutesFromElements,
} from 'react-router-dom';
// import { AllPosts, MyPosts, Login, Register} from "./components/index.js";

const { AllPosts, MyPosts, Login, Register } = lazy(() =>
  import('./components/index.js').then((module) => ({
    AllPosts: module.AllPosts,
    MyPosts: module.MyPosts,
    Login: module.Login,
    Register: module.Register,
  }))
);

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<Layout />}>
      <Route path="" element={<AllPosts />} />
      <Route path="/my-posts" element={<MyPosts />} />
      <Route path="/login" element={<Login />} />
      <Route path="/register" element={<Register />} />
    </Route>
  )
);

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Suspense fallback={<div className="text-5xl text-center">Loading</div>}>
      <RouterProvider router={router} />
    </Suspense>
  </React.StrictMode>
);

Solution

  • I never seen this kind of exporting, I fixed your code so here is what you need to do

    index.js

    import { lazy } from 'react';
    
    
    const Header = lazy(() => import('./Header'));
    const AllPosts = lazy(() => import('./AllPosts'));
    const MyPosts = lazy(() => import('./MyPosts'));
    const Login = lazy(() => import('./Login'));
    const Register = lazy(() => import('./Register'));
    
    export { Header, AllPosts, MyPosts, Login, Register };
    

    And in your main comonent

    import { AllPosts, MyPosts, Login, Register} from "./components/index.js";
    

    and remove this

    // remove this whole block of code, it is causing problems
    const { AllPosts, MyPosts, Login, Register } = lazy(() =>
      import('./components/index.js').then((module) => ({
        AllPosts: module.AllPosts,
        MyPosts: module.MyPosts,
        Login: module.Login,
        Register: module.Register,
      }))
    );
    

    I hope the link works https://stackblitz.com/edit/vitejs-vite-xebpki?file=src%2Fcomponents%2Findex.js,src%2Fmain.jsx