@babel/plugin-proposal-optional-chaining---可选链操作符兼容


NOTE: This plugin is included in @babel/preset-env, in ES2020

1. 安装依赖

npm:

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

yarn:

yarn add @babel/plugin-proposal-optional-chaining --dev

2. 配置

// With a configuration file (Recommended)
// .babelrc
{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}

3. 示例

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

 

4. 参考

https://babel.dev/docs/en/babel-plugin-proposal-optional-chaining#installation




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM