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

React Native项目中如何启用Array.prototype.with等ES2023数组方法?

React Native 0.72 启用 Array.prototype.with 等ES2023数组方法的解决方案

React Native 0.72 默认的 Babel 预设未包含 ES2023 数组方法的转译逻辑,即便 Node.js、TypeScript 本身支持这些方法,移动端 JS 引擎(如 Hermes、JSC)仍可能无法识别,因此需要通过配置 Babel 来启用转译。以下是具体解决步骤:

1. 安装 Babel 转译插件

Array.prototype.with 属于 ES 提案阶段的特性,需安装对应的转译插件:

npm install --save-dev @babel/plugin-proposal-array-with-replace
# 或使用 yarn
yarn add --dev @babel/plugin-proposal-array-with-replace

2. 修改 Babel 配置

在项目根目录的 babel.config.js 中,将插件添加到配置的 plugins 数组:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    '@babel/plugin-proposal-array-with-replace'
  ]
};

3. 确保 TypeScript 类型支持

虽然 TypeScript 5.2 已原生支持 ES2023 特性,仍建议在 tsconfig.json 的 compilerOptions.lib 中明确添加 ES2023 相关库,避免类型报错:

{
  "compilerOptions": {
    "lib": ["ES2023", "DOM"],
    // 其他已有配置...
  }
}

4. 验证配置生效

重启 Metro 服务并清除缓存:

npx react-native start --reset-cache

之后即可在代码中正常使用 Array.prototype.with,示例:

const arr = [1, 2, 3];
const newArr = arr.with(1, 4); // 输出 [1, 4, 3]

内容的提问来源于stack exchange,提问作者uloco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:53:16