Antd-dayjs-vite-plugin报错:TypeError: default不是函数
Vite启动报错TypeError: antd-dayjs-vite-plugin.default is not a function
问题场景
此前为解决Antd日历法语日期显示问题,使用antd-dayjs-vite-plugin在Vite项目中将Moment.js替换为Day.js,运行正常。但近期执行yarn dev时出现启动报错,升级插件版本(1.1.4→1.2.2)、升级Vite(2.5→3.1)后问题依旧,报错信息如下:
$ yarn dev yarn run v1.22.15 $ vite failed to load config from vite.config.ts error when starting dev server: TypeError: (0 , import_antd_dayjs_vite_plugin.default) is not a function [...]
当前vite.config.ts代码:
import reactRefresh from '@vitejs/plugin-react-refresh'; import antdDayjs from 'antd-dayjs-vite-plugin'; import { defineConfig } from 'vite'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [reactRefresh(), antdDayjs()], server: { host: process.env.HOST || '127.0.0.1', }, resolve: { alias: [{ find: '@', replacement: '/src' }], }, define: { __APP_VERSION__: JSON.stringify(process.env.npm_package_version), }, build: { commonjsOptions: { transformMixedEsModules: true, }, }, });
排查方案
1. 调整插件导入方式
部分版本的antd-dayjs-vite-plugin可能采用命名导出而非默认导出,尝试修改导入语句:
import { antdDayjs } from 'antd-dayjs-vite-plugin';
或使用混合导入方式兼容:
import * as antdDayjsPlugin from 'antd-dayjs-vite-plugin'; // 在plugins中使用 antdDayjsPlugin.default()
2. 清理依赖缓存
执行以下命令清理缓存并重新安装依赖:
yarn cache clean rm -rf node_modules rm package-lock.json yarn.lock yarn install
3. 验证版本兼容性
确认antd-dayjs-vite-plugin是否明确支持Vite 3.x,可暂时回退到Vite 2.x稳定版本(如2.9.x),搭配插件1.1.4测试是否恢复正常。
4. 手动配置Day.js替换规则
若插件仍无法正常工作,可绕过插件,直接在Vite中配置替换规则:
export default defineConfig({ resolve: { alias: [ { find: '@', replacement: '/src' }, { find: 'moment', replacement: 'dayjs' } ] }, define: { __APP_VERSION__: JSON.stringify(process.env.npm_package_version), 'process.env': {} }, optimizeDeps: { include: ['dayjs/plugin/customParseFormat', 'dayjs/plugin/localeData', 'dayjs/locale/fr'] } });
同时在项目入口文件(如src/main.tsx)手动引入Day.js适配:
import dayjs from 'dayjs'; import customParseFormat from 'dayjs/plugin/customParseFormat'; import localeData from 'dayjs/plugin/localeData'; import 'dayjs/locale/fr'; import dayjsGenerateConfig from 'rc-picker/lib/generate/dayjs'; import generatePicker from 'antd/es/date-picker/generatePicker'; import 'antd/es/date-picker/style/index'; dayjs.extend(customParseFormat); dayjs.extend(localeData); dayjs.locale('fr'); const DatePicker = generatePicker<dayjs.Dayjs>(dayjsGenerateConfig); export { DatePicker };
后续项目中使用该自定义DatePicker替代Antd原生组件即可。
内容的提问来源于stack exchange,提问作者Laurent Décamps
相关产品推荐
相关产品推荐

