跳至主内容

@babel/plugin-transform-optional-chaining(可选链转换插件)

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

信息

此插件已包含在 @babel/preset-env 中,属于 ES2020 标准。

示例

访问深层嵌套属性

JavaScript
const obj = {
foo: {
bar: {
baz: 42,
},
},
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined

// Optional chaining and normal chaining can be intermixed
obj?.foo.bar?.baz; // Only access `foo` if `obj` exists, and `baz` if
// `bar` exists

// Example usage with bracket notation:
obj?.["foo"]?.bar?.baz; // 42

调用深层嵌套函数

JavaScript
const obj = {
foo: {
bar: {
baz() {
return 42;
},
},
},
};

const baz = obj?.foo?.bar?.baz(); // 42

const safe = obj?.qux?.baz(); // undefined
const safe2 = obj?.foo.bar.qux?.(); // undefined

const willThrow = obj?.foo.bar.qux(); // Error: not a function

// Top function can be called directly, too.
function test() {
return 42;
}
test?.(); // 42

exists?.(); // undefined

构造深层嵌套的类

JavaScript
const obj = {
foo: {
bar: {
baz: class {
},
},
},
};

const baz = new obj?.foo?.bar?.baz(); // baz instance

const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined

const willThrow = new obj?.foo.bar.qux(); // Error: not a constructor

// Top classes can be called directly, too.
class Test {
}
new Test?.(); // test instance

new exists?.(); // undefined

删除深层嵌套属性

新增于:v7.8.0

JavaScript
const obj = {
foo: {
bar: {},
},
};

const ret = delete obj?.foo?.bar?.baz; // true

安装

npm install --save-dev @babel/plugin-transform-optional-chaining

用法

通过配置文件(推荐)

babel.config.json
{
"plugins": ["@babel/plugin-transform-optional-chaining"]
}

通过命令行

Shell
babel --plugins @babel/plugin-transform-optional-chaining script.js

通过 Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-optional-chaining"],
});

配置选项

loose

boolean,默认值 false

当设为 true 时,此转换将假设 document.all 不存在, 并执行与 null 的宽松相等性检查,而非严格检查 nullundefined

注意

建议迁移至顶层的 noDocumentAll 假设配置。

babel.config.json
{
"assumptions": {
"noDocumentAll": true
}
}

示例

输入

JavaScript
foo?.bar;

输出(noDocumentAll === true

JavaScript
foo == null ? void 0 : foo.bar;

输出(noDocumentAll === false

JavaScript
foo === null || foo === void 0 ? void 0 : foo.bar;
提示

你可以在此处阅读更多关于配置插件选项的信息。

参考