React中使用@aws-sdk/util-dynamodb的unmarshall方法报错求助
问题解答
核心结论
完全可以在React应用中使用@aws-sdk/util-dynamodb的unmarshall方法,你遇到的错误是因为React项目的打包工具(如Create React App)默认不会转译node_modules中的@aws-sdk包,而该包使用了未转译的ESNext语法(可选链、空值合并等),导致模块解析失败。
解决方案
方案1:修改打包配置,让Webpack转译@aws-sdk包(适用于Create React App)
如果你的React项目基于Create React App创建,可通过react-app-rewired修改配置,无需执行eject操作:
- 安装依赖:
npm install react-app-rewired customize-cra --save-dev
- 在项目根目录创建
config-overrides.js文件,添加以下内容:
const { override } = require('customize-cra'); module.exports = override( (config) => { // 让Webpack转译@aws-sdk相关模块 config.module.rules[1].oneOf.forEach(rule => { if (rule.include) { rule.include.push(/node_modules\/@aws-sdk/); } else { rule.include = [/node_modules\/@aws-sdk/]; } }); // 添加Babel插件支持ESNext语法 config.module.rules[0].use[0].options.plugins.push( '@babel/plugin-proposal-optional-chaining', '@babel/plugin-proposal-nullish-coalescing-operator' ); return config; } );
- 修改
package.json中的scripts命令:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }
- 重启开发服务器,重新安装依赖后即可正常使用
unmarshall。
方案2:使用第三方轻量工具替代
如果不想修改打包配置,可以使用无需转译的第三方DynamoDB序列化工具,比如dynamodb-marshaler:
- 安装依赖:
npm install dynamodb-marshaler --save
- 在代码中替换使用:
import { unmarshalItem } from 'dynamodb-marshaler'; import { useEffect, useState } from 'react'; useEffect(() => { const getGoal = async () => { try { const response = await api.get(apiUrl); // 注意:Items是数组,需要遍历每个item进行转换 const formattedItems = response.data.Items.map(item => unmarshalItem(item)); setGoal(formattedItems); } catch (err) { console.error(err); } }; getGoal(); }, []);
额外注意点
你的原代码存在逻辑问题:unmarshall方法仅能处理单个DynamoDB格式的item,而response.data.Items是数组,直接传递会导致转换失败。无论使用哪种方案,都需要遍历数组中的每个item分别转换。
内容的提问来源于stack exchange,提问作者Clarkie
相关产品推荐
相关产品推荐

