You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从CRA构建的React项目迁移到Vite时遇CommonJS模块兼容问题

CRA迁移Vite后CommonJS模块兼容问题解决方案

以下是针对你遇到的三个CommonJS模块兼容问题的具体解决方法:


1. textillate/letteringjs 导出报错

报错信息:The requested module '/node_modules/.vite/deps/letteringjs.js?v=d0ba45f7' does not provide an export named 'default'

解决步骤:

替换require为import,确保jQuery全局挂载正确,同时在Vite配置中强制将这两个模块转为ES模块处理。修改Textillate工具文件:

import $ from 'jquery';
import 'animate.css';
import 'letteringjs';
import 'textillate';

declare global {
    interface Window {
        jQuery: typeof $;
    }
}
window.jQuery = $;

const Textillate = () => {
    window.jQuery("#about").textillate({
        in: {
            effect: "animate__animated animate__flash",
            delay: 7,
            shuffle: true
        }
    });
};
export default Textillate;

报错信息:Cannot read properties of undefined (reading '__esModule')

解决步骤:

替换require为import,并在Vite配置中优化slick-carousel的依赖处理。修改Slick工具文件:

import $ from 'jquery';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import 'slick-carousel';

declare global {
    interface Window {
        jQuery: typeof $;
    }
}
window.jQuery = $;

const Slick = () => {
    window.jQuery("#projects").slick({
        infinite: true,
        speed: 500,
        autoplay: true,
        autoplaySpeed: 1500,
        fade: true,
        cssEase: 'linear'
    });
}
export default Slick;

3. particle-js 函数未定义报错

报错信息:particlesJS is not a function

解决步骤:

particles.js在Vite下的正确导入方式是直接导入particlesJS函数,而非依赖全局window.pJS。修改Contact组件:

import React from 'react';
import particlesJS from 'particles.js';
import Prtcl from '../utils/Particles';
import { useInView } from 'react-intersection-observer';

const Contact: React.FC = () => {
    const [ref, inView] = useInView({
        triggerOnce: true,
        threshold: .5
    });
    React.useEffect(() => {
        if (inView) {
            particlesJS("particles-js", Prtcl);
        }
    }, [inView]);

    // 组件其余代码...
};
export default Contact;

同时可删除Particles工具文件中的全局pJS声明,因为已直接导入函数。


最终Vite配置调整(vite.config.ts)

移除无效的vite-plugin-require,添加CommonJS模块优化配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    commonjsOptions: {
      include: ['textillate', 'letteringjs', 'slick-carousel', 'particles.js']
    }
  },
  resolve: {
    alias: {
      'jquery': 'jquery/dist/jquery.min.js'
    }
  }
});

内容的提问来源于stack exchange,提问作者VireZee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 04:58:23