@babel/plugin-transform-new-target
info
这个插件包含在 @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();
}
}
此外,当使用带有 ES5 函数类(转换后的 ES6 类)的 newTarget 时,这个插件不能转换所有的 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
- Bun
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
bun add --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"],
});