@babel/plugin-transform-new-target
信息
此插件包含在 @babel/preset-env
中
示例
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
注意事项
此插件依赖于 this.constructor
,这意味着在使用未转换的类时,必须已经调用了 super
。
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
情况。
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)
安装
- 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
用法
使用配置文件(推荐)
babel.config.json
{
"plugins": ["@babel/plugin-transform-new-target"]
}
通过 CLI
Shell
babel --plugins @babel/plugin-transform-new-target script.js
通过 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-new-target"],
});