@babel/plugin-transform-nullish-coalescing-operator
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
信息
此插件已包含在 @babel/preset-env 中,属于 ES2020 标准。
示例
输入
JavaScript
var foo = object.foo ?? "default";
输出
JavaScript
var _object$foo;
var foo =
(_object$foo = object.foo) !== null && _object$foo !== void 0
? _object$foo
: "default";
备注
此处不能使用 != null,因为 document.all == null 成立,
但 document.all 不被视为"空值"。
安装
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-nullish-coalescing-operator
yarn add --dev @babel/plugin-transform-nullish-coalescing-operator
pnpm add --save-dev @babel/plugin-transform-nullish-coalescing-operator
bun add --dev @babel/plugin-transform-nullish-coalescing-operator
用法
通过配置文件(推荐)
babel.config.json
{
"plugins": ["@babel/plugin-transform-nullish-coalescing-operator"]
}
通过命令行
Shell
babel --plugins @babel/plugin-transform-nullish-coalescing-operator script.js
通过 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-nullish-coalescing-operator"],
});
配置选项
loose
boolean,默认值 false
当设为 true 时,此转换将假设 document.all 不存在,
并执行与 null 的宽松相等性检查,而非严格检查 null 和 undefined。
注意
建议迁移至顶层的 noDocumentAll 假设配置。
babel.config.json
{
"assumptions": {
"noDocumentAll": true
}
}
示例
输入
JavaScript
var foo = object.foo ?? "default";
输出
JavaScript
var _object$foo;
var foo = (_object$foo = object.foo) != null ? _object$foo : "default";
提示
你可以在此处阅读更多关于配置插件选项的信息。