Skip to content

语法降级

Oxc 变换器支持将 ESNext 语法降级为 ES2015 语法。

目标环境

Oxc 变换器接收一个 target 选项,用于指定目标运行时环境。这将决定哪些语法会被降级,以及会发出哪些警告。

每个目标环境由环境名称后跟版本号组成。当前支持的环境名称如下:

  • chrome
  • deno
  • edge
  • firefox
  • hermes
  • ie
  • ios
  • node
  • opera
  • rhino
  • safari
  • samsung
  • es

支持 esbuild 的 target 选项 中的值,但不包括 ES5。

js
import { transform } from "oxc-transform";

const result = await transform("lib.js", "const foo = a ?? b;", {
  target: ["chrome87", "es2022"],
});

降级转换

Oxc 支持对以下语法进行降级。请注意,与正则表达式相关的转换仅将正则字面量(/foo/v)转换为使用 RegExp 构造函数(new RegExp('foo', 'v'))的形式。你仍需配合使用兼容性垫片以支持较老的浏览器。

ES2026

  • 显式资源管理(using a = foo()

ES2024

  • 正则表达式 v 标志与集合表示法 + 字符串属性(/\p{Emoji}--\p{ASCII}/v

ES2022

  • 类静态块(class A { static { foo() } }
  • 类字段(class A { foo = 1; #bar = 2; static baz = 3; static qux = 4; foobar(a) { return #bar in a } }
  • 正则表达式匹配索引(/foo/d

ES2021

  • 逻辑赋值运算符(foo ||= bar
  • 数字分隔符(注意:这不是通过转换实现的,但代码生成始终会移除这些分隔符)

ES2020

  • 空值合并操作符(foo ?? bar
  • 可选链(foo?.bar
  • 从模块导出命名空间(export * as foo from "bar"

ES2019

  • 可选的 catch 绑定(try {} catch {}

ES2018

  • 剩余/展开属性(const foo = { a, b, ...c }const { x, y, ...z } = foo;
  • 异步迭代(for await (const x of y) {}async function* foo() {}
  • 正则表达式 Unicode 属性转义(/\p{Script=Greek}/u
  • 正则表达式后瞻断言(/(?<=foo)bar/
  • 正则表达式命名捕获组(/(?<foo>bar)/
  • 正则表达式的 sdotAll)标志(/foo./s

ES2017

  • 异步函数(async function foo() {}

ES2016

  • 指数运算符(foo ** bar

ES2015

  • 箭头函数(const foo = () => {}
  • 正则表达式粘滞标志(/foo/y
  • 正则表达式 Unicode 标志(/foo/u

警告信息

当目标运行时不支持以下语法时,Oxc 变换器会发出警告。

ES2022

  • 顶层 awaitawait foo()
  • 任意模块命名空间标识符(import * as "f o o" from "bar"

ES2020

  • BigInt(1n

编译器假设

你可以指定一些编译器假设,使输出更小。

js
import { transform } from "oxc-transform";

const result = await transform("lib.js", "const foo = a ?? b;", {
  target: ["chrome87", "es2022"],
  assumptions: {
    noDocumentAll: true,
  },
});

支持以下假设。

noDocumentAll

假设已弃用的 document.all 及其特殊行为未被使用。

pureGetters

假设访问器(getters)没有副作用。

setPublicClassFields

在使用公共类字段时,假设它们不会遮蔽当前类、其子类或其父类中的任何访问器。因此,可以直接赋值,而无需使用 Object.defineProperty

说明

对于 TypeScript,如果你希望行为等同于 useDefineForClassFields: false,你应该同时将 setPublicClassFieldsremoveClassFieldsWithoutInitializer 设置为 true。 有关更多信息,请参阅 TypeScript 页面

不支持的语法

以下语法不会被 Oxc 变换器降级。