@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



posted @ 2022-04-21 16:07  VictoriaC~  阅读(2950)  评论(0编辑  收藏  举报