skip to Main Content

I tried to build a React PWA by vite. In the development everything is ok,but the error of title shows on the production mode.
enter image description here

I guss if the version of react,react-router-dom,vite do not compatible.Here is my package.json

{
  "name": "vite-react-ts-tpl",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^2.2.3",
    "antd": "^5.16.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^9.1.0",
    "react-router-dom": "^6.23.0"
  },
  "devDependencies": {
    "@types/node": "^20.12.5",
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@typescript-eslint/eslint-plugin": "^7.5.0",
    "@typescript-eslint/parser": "^7.5.0",
    "@vitejs/plugin-react": "^4.2.1",
    "axios": "^1.6.8",
    "eslint": "^8.57.0",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-prettier": "^5.1.3",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.6",
    "less": "^4.2.0",
    "less-loader": "^12.2.0",
    "prettier": "^3.2.5",
    "stylelint": "^16.3.1",
    "stylelint-config-standard": "^36.0.0",
    "typescript": "^5.2.2",
    "vite": "^5.2.10",
    "vite-plugin-dynamic-import": "^1.5.0"
  }
}

Here is my vite config file.

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import dynamicImport from 'vite-plugin-dynamic-import';

export default defineConfig({
    plugins: [react(), dynamicImport()],
    resolve: {
        /*配置别名 */
        alias: {
            '@': path.resolve(__dirname, 'src'),
        },
    },
    base: '/',
    server: {
        port: 2024,
    },
    build: {
        dynamicImportVarsOptions: {},
    },
    esbuild: {
        pure: ['console.log', 'debugger'],
    },
    css: {
        preprocessorOptions: {
            less: {
                modifyVars: {
                    hack: `true; @import (reference) "${path.resolve('src/assets/css/common.less')}";`,
                },
                javascriptEnabled: true,
            },
        },
    },
});

I tried to solve this problem for a while.I found this code causes the error.

export const lazyLoad = (path: string) => {
    const Module = lazy(() => import(`../${path}`));

    return (
        <Suspense fallback={<div>Loading...</div>}>
            <Module />
        </Suspense>
    );
};

I use the React.lazy to load react router dynamic. The backend returns object include the varible of path, title and others.

Please help child! This problem has been bothering me for a long time.

To sole this problem.

2

Answers


  1. Chosen as BEST ANSWER

    final soled it by import.meta.glob

    if your pages are in the pages folder.You can code like this.

    import { Spin } from 'antd';
    import { Suspense, lazy } from 'react';
    import { Navigate, RouteObject } from 'react-router-dom';
    
    const modules = import.meta.glob('../pages/**/index.tsx');
    
    export function LazyImportComponent(action: any, loading?: React.ReactNode) {
        const LazyComponent = lazy(action);
        return (props: Record<string, any>) => {
            return (
                <Suspense fallback={loading ? loading : <Spin></Spin>}>
                    <LazyComponent {...props} />
                </Suspense>
            );
        };
    }
    
    export function lazyLoad(path: string, props: Record<string, any> = {}) {
        const MyComponent = LazyImportComponent(modules[`../pages/${path}/index.tsx`]);
        return <MyComponent {...props} />;
    }
    
    const Appraisal = () => {
        const token = localStorage.getItem('token');
        const backendPath = 'main';
        return token ? lazyLoad(backendPath) : <Navigate to='/login' />;
    };
    
    const router: RouteObject[] = [
        {
            path: '/',
            element: <Appraisal />,
            children: [],
        },
        {
            path: '/login',
            element: lazyLoad('login'),
        },
        {
            path: '*',
            element: lazyLoad('loading'),
        },
    ];
    
    export { router };
    
    

    The LazyImportComponent and lazyLoad is the core.


  2. I’m sure React.lazy and Suspense by themselves should not cause such issues, but dynamically imported modules may have side effects or require special handling that is not visible in development mode.

    Could you please confirm if the error persists when you execute the tsc and vite build commands on your local machine? 

    If it does, one way to isolate the issue is to temporarily disable minification in your Vite production build.

    Minification, along with tree shaking, is a part of the production optimization process in Vite, and it can sometimes introduce behaviors that are not present during development. I suggest these steps are intended to aid in diagnosing the issue.

    Have you checked the dynamically imported module to see if any properties are changing?

    Also, since I noticed you’re using Redux, make sure that the state is not changed directly. Direct state mutation is a common source of errors, as Redux expects the state to be immutable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search