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

如何修复构建AWS Cognito浏览器端JS时的导出与配置报错

解决AWS Cognito无框架前端注册登录的构建与运行错误

问题背景与现象

后端使用AWS Cognito User Pools,前端无任何JavaScript框架,通过webpack打包aws-amplify实现注册登录功能时,遇到两个问题:

  • 构建阶段警告:WARNING in ./src/app.js 18:22-36 export 'Auth' (imported as 'Auth') was not found in 'aws-amplify' (possible exports: Amplify)
  • 测试阶段Chrome控制台错误:Uncaught TypeError: Cannot read properties of undefined (reading 'loginWith'),错误源自Amplify.mjs第90行的if (!this.resourcesConfig.Auth?.Cognito.loginWith?.oauth ||代码

解决方案

1. 修复Auth模块导入错误(解决构建警告)

AWS Amplify v6+版本调整了模块结构,Auth不再从根包aws-amplify导出,需要单独安装并导入专属包:

  1. 安装依赖:
npm install @aws-amplify/auth
  1. 修改src/app.js的导入代码:
// 旧代码
import { Amplify, Auth } from 'aws-amplify';

// 新代码
import { Amplify } from 'aws-amplify';
import { Auth } from '@aws-amplify/auth';

2. 修复Cognito配置格式错误(解决运行时loginWith错误)

Amplify v6要求Auth配置采用嵌套结构,原有的扁平化配置会导致resourcesConfig.Auth.Cognito未定义,进而触发loginWith读取错误。使用符合v6规范的配置格式:

Amplify.configure({
  Auth: {
    Cognito: {
      // 替换为你的实际参数
      userPoolId: 'us-east-1_XXXXXXXXX',
      userPoolClientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
      region: 'us-east-1',
      // 明确配置允许的登录方式,避免undefined
      loginWith: {
        username: true,
        password: true,
        oauth: {} // 若不使用OAuth,保留空对象防止读取报错
      }
    }
  }
});

3. 补充Webpack配置(可选,针对模块解析问题)

如果Webpack无法正确解析Amplify的.mjs模块,在webpack.config.js中添加扩展名解析规则:

module.exports = {
  // 其他已有配置
  resolve: {
    extensions: ['.mjs', '.js', '.json']
  }
};

内容的提问来源于stack exchange,提问作者Sean B. Durkin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:03:27