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

Vite/React生产构建中MediaPipe FaceDetection构造函数报错问题

Vite React/TypeScript生产构建中MediaPipe人脸检测构造函数错误问题

在基于Vite的React/TypeScript应用中使用MediaPipe实现人脸检测功能时,开发模式(npm run dev)运行完全正常,但执行生产构建并启动服务(npm run build)时,出现如下构造函数错误:

Uncaught TypeError: face_detection.FaceDetection is not a constructor
at main-CLsce9aG.js:31922:48179
at Qj (main-CLsce9aG.js:38:27193)
at Hk (main-CLsce9aG.js:38:47511)
at main-CLsce9aG.js:38:45609
at X_ (main-CLsce9aG.js:23:1729)
at MessagePort.p2 (main-CLsce9aG.js:23:2141)

用户代码如下:

import * as FaceDetection from '@mediapipe/face_detection';

export const useFaceDetection = (options: FaceDetectionOptions = {}): UseFaceDetectionReturn => {
  useEffect(() => {
    const faceDetection = new FaceDetection.FaceDetection({
      locateFile: (file) => {
        return `https://cdn.jsdelivr.net/npm/@mediapipe/face_detection@0.4/${file}`;
      }
    });
    // ... 其余代码
  });
}

用户的两个疑问:

  1. 为何FaceDetection构造函数在生产构建中不可用?
  2. 如何在Vite/React生产构建中正确初始化MediaPipe人脸检测?

回答

1. 构造函数在生产构建中不可用的原因

Vite生产构建时默认开启tree-shaking优化,而MediaPipe的包结构存在ESM与UMD模块的兼容性问题,tree-shaking可能误剔除了FaceDetection构造函数相关的代码。另外,生产构建的代码压缩、模块打包过程可能破坏了MediaPipe原有的导出结构,导致无法正确访问构造函数。

2. 生产环境正确初始化的解决方法

提供两种可行方案:

方案一:调整导入方式并配置Vite优化规则

  • 修改导入语句,直接导入目标构造函数:
    import { FaceDetection } from '@mediapipe/face_detection';
    
  • 在vite.config.ts中添加配置,禁止对MediaPipe包进行tree-shaking处理:
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      build: {
        rollupOptions: {
          external: ['@mediapipe/face_detection'],
          output: {
            globals: {
              '@mediapipe/face_detection': 'FaceDetection'
            }
          }
        }
      }
    });
    

方案二:使用动态导入加载模块

通过动态导入的方式,确保MediaPipe模块在生产环境中被正确加载,规避tree-shaking的影响:

import { useEffect } from 'react';

export const useFaceDetection = (options: FaceDetectionOptions = {}): UseFaceDetectionReturn => {
  useEffect(() => {
    const initFaceDetection = async () => {
      const { FaceDetection } = await import('@mediapipe/face_detection');
      const faceDetection = new FaceDetection({
        locateFile: (file) => {
          return `https://cdn.jsdelivr.net/npm/@mediapipe/face_detection@0.4/${file}`;
        }
      });
      // ... 后续初始化逻辑
    };
    initFaceDetection();
  }, []);

  // ... 其余代码
};

另外要注意,locateFile指向的CDN资源版本必须与本地安装的@mediapipe/face_detection版本完全一致,避免版本不匹配引发加载错误。


内容的提问来源于stack exchange,提问作者amal m reji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:17:17