Vite React项目集成aws-sdk生产环境报't is not a constructor'错误如何解决?
Vite React 项目中使用 aws-sdk 生产环境报错'Uncaught type error: t is not a constructor'的解决方案
问题场景
在Vite React项目中使用aws-sdk v2,本地构建正常,但生产环境运行时抛出Uncaught type error: t is not a constructor,尝试展开导入、开启sourcemap均无法解决。
解决方法
1. 改用 AWS SDK v3(推荐方案)
aws-sdk v2为Node.js设计,在浏览器环境打包易出现兼容性问题;v3采用模块化设计,更适配前端场景,体积更小且兼容性更好。
步骤:
- 安装所需依赖:
npm install @aws-sdk/client-s3 @aws-sdk/lib-storage
- 替换原有代码:
import { S3Client } from "@aws-sdk/client-s3"; import { Upload } from "@aws-sdk/lib-storage"; // 初始化S3客户端 const s3Client = new S3Client({ credentials: { accessKeyId: import.meta.env.VITE_WASABI_ACCESS_KEY, secretAccessKey: import.meta.env.VITE_WASABI_SECRET_KEY, }, endpoint: "https://s3.ap-northeast-2.wasabisys.com", forcePathStyle: true, }); // 上传函数改造 const handleUploadFile = async ( file: File | string | undefined | null, type: 'identified' | 'deidentified', ): Promise<string> => { if (!file || typeof file === 'string') return file || ''; if (!file?.type) return file.name; const [compFile, compExt] = await compress(file); const filename = fileName(file.name, compExt); const filePath = `subjects/${id}/${type}/${filename}`; const uploadParams = { Bucket: import.meta.env.VITE_WASABI_BUCKET_NAME, Key: filePath, Body: compFile, ACL: 'public-read', }; const upload = new Upload({ client: s3Client, params: uploadParams, }); // 监听上传进度 upload.on("httpUploadProgress", (evt) => { const progress = evt.loaded / (evt.total ?? Number.MAX_SAFE_INTEGER); if (progress < 1) { return toast.loading( <div className='flex flex-col gap-2'> <p className='text-xs'>Uploading {file.name}</p> <Progress progress={Math.ceil(progress * 100)} /> </div>, { id: file.name }, ); } toast.success(<p className='text-xs'>Uploaded {file.name}</p>, { id: file.name }); }); try { await upload.done(); return filePath; } catch (err) { console.error('Error', err); throw new Error(err.message || 'failed'); } };
2. 坚持使用 aws-sdk v2 的调整方案
如果不想升级到v3,可以通过以下配置修复压缩导致的构造函数识别问题:
调整Vite构建配置
修改vite.config.js中的build选项,禁用terser对类名和函数名的压缩:
export default defineConfig({ // ...其他配置 build: { minify: 'terser', terserOptions: { keep_classnames: true, // 保留类名 keep_fnames: true // 保留函数名 }, rollupOptions: { plugins: [nodePolyfills()], }, }, });
调整导入方式
替换原有解构导入为整体导入:
import AWS from 'aws-sdk'; const { S3, Endpoint } = AWS; // 初始化实例 const s3 = new S3({ accessKeyId: import.meta.env.VITE_WASABI_ACCESS_KEY, secretAccessKey: import.meta.env.VITE_WASABI_SECRET_KEY, s3ForcePathStyle: true, endpoint: new Endpoint('https://s3.ap-northeast-2.wasabisys.com'), });
3. 验证环境变量有效性
生产环境中确认VITE_WASABI_ACCESS_KEY、VITE_WASABI_SECRET_KEY等环境变量已正确注入,避免因变量缺失导致实例初始化异常。
内容的提问来源于stack exchange,提问作者Bayrsaihan Tergeltengis
相关产品推荐
相关产品推荐

