Skip to content

语法降级

Oxc transformer 支持将 ESNext 语法降级到 ES2015。

目标环境

Oxc transformer 接受一个 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: "es2020",
  // 或多个目标:
  // target: ["chrome87", "es2022"],
});

转换

Oxc 支持降级以下语法。请注意,与 RegExp 相关的转换仅将 RegExp 字面量(/foo/v)转换为使用 RegExp 构造函数(new RegExp('foo', 'v'))。您需要配合使用 polyfill 来支持旧版浏览器。

ES2026

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

ES2024

  • 带有集合表示法 + 字符串属性的 RegExp 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 } }
  • RegExp 匹配索引(/foo/d

ES2021

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

ES2020

  • 空值合并运算符(foo ?? bar
  • 可选链(foo?.bar
  • 导出命名空间(export * as foo from "bar"

ES2019

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

ES2018

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

ES2017

  • Async 函数(async function foo() {}

ES2016

  • 指数运算符(foo ** bar

ES2015

  • 箭头函数(const foo = () => {}
  • RegExp 粘性标志(/foo/y
  • RegExp unicode 标志(/foo/u

警告

如果目标运行时不支持以下语法,Oxc transformer 会发出警告。

ES2022

  • 顶层 await(await 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,
  },
});

支持以下假设。

ignoreFunctionLength

假设没有代码依赖函数对象的 .length 属性。

注意

此假设尚未完全实现。特别是,在对象 rest/spread 中启用它当前会产生转换错误。

noDocumentAll

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

objectRestNoSymbols

假设对象 rest/spread 属性不包括 Symbol 键。

注意

此假设尚未完全实现。特别是,在对象 rest/spread 中启用它当前会产生转换错误。

pureGetters

假设 getter 没有副作用。

setPublicClassFields

使用公共类字段时,假设它们不会遮蔽当前类、其子类或其父类中的任何 getter。因此,使用赋值而不是 Object.defineProperty 是安全的。

注意

对于 TypeScript,如果您想要的行为等同于 useDefineForClassFields: false,您应该同时将 setPublicClassFieldsremoveClassFieldsWithoutInitializer 设置为 true。 详见 TypeScript 页面

不支持的语法

以下语法不会被 Oxc transformer 降级。