@babel/plugin-transform-new-target
信息
此插件包含在 @babel/preset-env
中
¥This plugin is included in @babel/preset-env
示例
¥Example
JavaScript
function Foo() {
console.log(new.target);
}
Foo(); // => undefined
new Foo(); // => Foo
JavaScript
class Foo {
constructor() {
console.log(new.target);
}
}
class Bar extends Foo {}
new Foo(); // => Foo
new Bar(); // => Bar
注意事项
¥Caveats
这个插件依赖于 this.constructor
,这意味着在使用未转换的类时必须已经调用了 super
。
¥This plugin relies on this.constructor
, which means super
must
already have been called when using untransformed classes.
JavaScript
class Foo {}
class Bar extends Foo {
constructor() {
// This will be a problem if classes aren't transformed to ES5
new.target;
super();
}
}
此外,当使用 newTarget
和 ES5 函数类(转换的 ES6 类)时,此插件无法转换所有 Reflect.construct
案例。
¥Additionally, this plugin cannot transform all Reflect.construct
cases
when using newTarget
with ES5 function classes (transformed ES6 classes).
JavaScript
function Foo() {
console.log(new.target);
}
// Bar extends Foo in ES5
function Bar() {
Foo.call(this);
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
// Baz does not extend Foo
function Baz() {}
Reflect.construct(Foo, []); // => Foo (correct)
Reflect.construct(Foo, [], Bar); // => Bar (correct)
Reflect.construct(Bar, []); // => Bar (incorrect, though this is how ES5
// inheritance is commonly implemented.)
Reflect.construct(Foo, [], Baz); // => undefined (incorrect)
安装
¥Installation
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-new-target
yarn add --dev @babel/plugin-transform-new-target
pnpm add --save-dev @babel/plugin-transform-new-target
用法
¥Usage
使用配置文件(推荐)
¥With a configuration file (Recommended)
babel.config.json
{
"plugins": ["@babel/plugin-transform-new-target"]
}
通过 CLI
¥Via CLI
Shell
babel --plugins @babel/plugin-transform-new-target script.js
通过 Node API
¥Via Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-new-target"],
});