@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();
}
}
此外,此外掛無法轉換所有 Reflect.construct
案例,當使用 newTarget
與 ES5 函式類別(轉換後的 ES6 類別)時。
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"],
});