如何将ECMAScript 12代码转换为兼容ECMAScript 10的版本
ES12 代码降级到 ES10 转换方案
在线转换工具
- 首选 Babel 官方在线 REPL 工具,无需本地配置,直接粘贴代码后在预设项中把目标环境设置为支持 ES10 的版本,即可一键导出兼容 ES10 的代码。
- 也可使用各类前端在线编译平台,选择 ES 版本降级配置完成转换。
手动转换方案
你可以对照 ES12 相较于 ES10 新增的特性逐一修改,常见需要调整的语法如下:
1. 逻辑赋值运算符(&&=、||=、??=)
ES12 写法示例:
a &&= b a ||= b a ??= b
转换为 ES10 写法:
a = a && b a = a || b if (a === null || a === undefined) a = b
2. 数值分隔符
ES12 允许用下划线分隔数值提升可读性:
const total = 1_000_000
直接删除下划线即可兼容 ES10:
const total = 1000000
3. String.prototype.replaceAll()
ES12 写法:
str.replaceAll('old', 'new')
ES10 可以用带全局标记的正则替换实现:
// 固定匹配值写法 str.replace(/old/g, 'new') // 动态匹配值写法 str.replace(new RegExp(searchStr, 'g'), replaceStr)
4. Promise.any() 与 AggregateError
这两个是 ES12 新增的 API,ES10 没有原生支持,可以自行实现 polyfill 注入:
// 先实现 AggregateError polyfill if (typeof AggregateError === 'undefined') { window.AggregateError = function(errors, message) { this.name = 'AggregateError' this.message = message || '' this.errors = errors } AggregateError.prototype = Error.prototype } // 实现 Promise.any polyfill if (!Promise.any) { Promise.any = function(promiseList) { return new Promise((resolve, reject) => { const len = promiseList.length let rejectCount = 0 const errors = [] if (len === 0) return reject(new AggregateError([], 'All promises were rejected')) promiseList.forEach((p, index) => { Promise.resolve(p) .then(resolve) .catch(err => { errors[index] = err rejectCount++ if (rejectCount === len) { reject(new AggregateError(errors, 'All promises were rejected')) } }) }) }) } }
5. 类私有属性(# 开头的私有成员)
ES12 写法:
class User { #password = '123456' getPassword() { return this.#password } }
ES10 可以用 Symbol 模拟私有属性:
const _password = Symbol('password') class User { constructor() { this[_password] = '123456' } getPassword() { return this[_password] } }
6. ES11 新增语法兼容
ES10 也不支持 ES11 新增的可选链(?.)和空值合并运算符(??),如果你的代码里用到了这两个特性也需要转换:
- 可选链
user?.info?.age转换为user && user.info && user.info.age - 空值合并运算符
val ?? defaultValue转换为val !== null && val !== undefined ? val : defaultValue
如果代码量较大,优先使用在线工具完成整体转换后再做少量校验即可,效率远高于全手动修改。
内容的提问来源于stack exchange,提问作者Random Kindle
相关产品推荐
相关产品推荐

