Vite React TypeScript集成AWS Amplify导入aws-exports.js报错求助
解决Vite + TypeScript React中AWS Amplify的
aws-exports.js导入错误 问题原因
amplify init自动生成的aws-exports.js采用CommonJS格式导出(module.exports = { default: awsmobile }),而Vite默认以ES模块规则解析文件,导致默认导入语法无法识别该导出结构,抛出Uncaught SyntaxError: The requested module '/src/aws-exports.js' does not provide an export named 'default'错误。
有效解决方案
方案1:调整导入语法适配CommonJS导出
直接在main.tsx中修改导入方式,明确获取导出对象中的default属性:
import { Amplify } from "aws-amplify"; import * as awsExports from "./aws-exports"; Amplify.configure(awsExports.default);
方案2:配置Vite解析规则
在vite.config.ts中添加配置,让Vite正确识别aws-exports.js的CommonJS格式:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], optimizeDeps: { include: ['aws-exports'], esbuildOptions: { loader: { '.js': 'jsx', }, }, }, resolve: { alias: { './aws-exports': './aws-exports.js', }, }, })
方案3:修正TypeScript声明文件
调整aws-exports.d.ts的内容,正确映射文件的导出结构:
declare const awsmobile: Record<string, any>; declare module './aws-exports' { export default awsmobile; }
注意:不要手动修改
aws-exports.js文件,该文件会被AWS Amplify自动覆盖,所有修改都会丢失。
内容的提问来源于stack exchange,提问作者ikonuk
相关产品推荐
相关产品推荐

