[Fixed] Error in production build with Vite & React: Error in Uncaught TypeError: _ is not a function – Vite

by
Ali Hasan
axios laravel-vite production-environment react-typescript reactjs

Quick Fix: Change the import statement; from import * as dayjs from "dayjs"; to import dayjs from "dayjs"; import customParseFormat from "dayjs/plugin/customParseFormat"; .

The Problem:

In a production build using Vite and React, an error occurs that reads "_ is not a function" due to a missing dependency. Despite the app running smoothly in development mode, the production build fails to load.

The Solutions:

Solution 1: Import the Day.js library correctly.

The error was caused by importing the Day.js library incorrectly. The library should be imported as follows:

import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";

instead of:

import * as dayjs from "dayjs";
import * as customParseFormat from "dayjs/plugin/customParseFormat";

The latter import syntax is not compatible with the production build process.

Solution 2: Update Vite Configuration for React App Conversion

If you are migrating from Vite with React and TypeScript to a create-react-app with TypeScript template, you need to update your Vite configuration to align with the create-react-app settings.

Specifically, you should convert the environment variable references as follows:

Vite create-react-app
import.meta.env.VITE_ENV_NAME process.env.REACT_APP_ENV_NAME

After making these changes, build and run the application locally to ensure that the issue has been resolved.

Q&A

Is there any difference between vite configuration and create-react-app configuration ?

vite – import.meta.env.VITE_ENV_NAME cra – process.env.REACT_APP_ENV_NAME

while building with vite and typescript , it shows error in production build with vite & react: error in Uncaught TypeError: _ is not a function, how to fix it?

The error was coming while importing some day.js library , so the correct import method would be : import dayjs from "dayjs"; import customParseFormat from "dayjs/plugin/customParseFormat";

Video Explanation:

The following video, titled "Vite Build 101 - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Coding Shorts: Building with Vite - Customizing Production Builds ... React Proxy | Easiest Fix to CORS Errors. Sam Meech-Ward•61K views · 19 ...