1 安装插件
npm install @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-nullish-coalescing-operator --save-dev
2 babel.config.js 文件配置插件
module.exports = {
plugins: [
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-nullish-coalescing-operator',
],
};
3 使用说明
(?. )可选链 :判断对象是否存在属性,不存在返回undefind, 存在则返回该属性值
let res = {}
let bool = res ?. title // 返回 undefined
let res2 = {title: '测试'}
let bool = res2 ?. title // 返回 测试
(??) 双问号语法 :当左边的值为null 或者 undefined时,返回右边的值
let bool = null ?? true; // 返回 true