React.js + Vite: failed to fetch dynamically imported module

I’m having an issue with my React project using code splitting.

For reference I’m using:

  • React 18.2.0
  • Vite 5.2.0

I need to load some components dynamically based on some redux state. It’s working on local but its failing on prod.

To understand how its working, this loads on a certain route, lets say ‘/sample’ and from the left hand side you select a question and its loaded onto the container (The click sets the state on redux that its used on this component), based on the import route, the react router routes are not affected by this import.

  const LoadedQuestion = useMemo(() => {
    let importPath = '';

    const questionAvailableIn = question?.availableIn
      ? getQuestionnaireTypeName(Math.min(...question?.availableIn))
      : undefined;

    if (questionAvailableIn) {
      importPath = `../../../components/Questions/${questionnaireType}/${loadedQuestionComponent?.section}/${loadedQuestionComponent?.question}/index.tsx`;
    } else {
      importPath = `../../../components/Questions/${loadedQuestionComponent?.section}/${loadedQuestionComponent?.question}/index.tsx`;
    }

    return loadedQuestionComponent?.section
      ? React.lazy(() => import(/* @vite-ignore */ importPath))
      : React.lazy(
          () =>
            import(
              /* @vite-ignore */ `../../../components/Questions/Default.tsx`
            )
        );
  }, [loadedQuestionComponent, questionnaireType]);

I’m using React.lazy to import as you see based on some variables from redux state. this is the render

  return (
    <div className={`flex justify-center h-full ${styles.container}`}>
      <div>
        <Suspense fallback={<div></div>}>
          <div className={`${styles.fontCustom} p-20`}>
            <Fade>
              <LoadedQuestion question={question ? question : {}} />
            </Fade>
          </div>
        </Suspense>
      </div>
    </div>
  );

When I run this on local it works great but it fails on prod somehow returning the failed to fetch dynamically error.

This is my vite.config file:

import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import tsconfigPaths from 'vite-tsconfig-paths';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    define: {
      'process.env.REACT_APP_BASE_URL_FIREBASE': JSON.stringify(
        env.REACT_APP_BASE_URL_FIREBASE
      ),
    },
    plugins: [react(), tsconfigPaths()],
    root: 'src',
    build: {
      outDir: '../dist',
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './'),
      },
    },
  };
});

Any ideas?? I already saw some SO threads on this, I tried the solutions but still nothing. Thanks in advance.

I cannot use static import, I know that it would probably solve the issue but its not viable, I need to code split.

I also tried the @ defined in the alias for vite. Works great for importing assets like svg, somehow with React.lazy and import its not working.

I also tried to re import with retries but still unsucessful.

import React from 'react';

export const lazyWithRetries: typeof React.lazy = (importer) => {
  const retryImport = async () => {
    try {
      return await importer();
    } catch (error: any) {
      for (let i = 0; i < 5; i++) {
        await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** i));
        const url = new URL(
          error.message
            .replace('Failed to fetch dynamically imported module: ', '')
            .trim()
        );
        url.searchParams.set('t', `${+new Date()}`);

        try {
          return await import(url.href);
        } catch (e) {
          console.log('retrying import');
        }
      }
      throw error;
    }
  };
  return React.lazy(retryImport);
};

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật