跳到主要內容

@babel/plugin-transform-optional-chaining

資訊

這個外掛包含在 @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"]
}

透過 CLI

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

布林值,預設為 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;
提示

您可以在 這裡 閱讀更多關於設定外掛程式選項的資訊。

參考資料