Below is a class with four class properties which will be transformed.
class Bork {
//Property initializer syntax
instanceProperty = "bork";
boundFunction = () => {
return this.instanceProperty;
}
//Static class properties
static staticProperty = "babelIsCool";
static staticFunction = function() {
return Bork.staticProperty;
}
}
let myBork = new Bork;
//Property initializers are not on the prototype.
console.log(myBork.__proto__.boundFunction); // > undefined
//Bound functions are bound to the class instance.
console.log(myBork.boundFunction.call(undefined)); // > "bork"
//Static function exists on the class.
console.log(Bork.staticFunction()); // > "babelIsCool"
npm install --save-dev babel-plugin-transform-class-properties
.babelrc
(Recommended).babelrc
// without options
{
"plugins": ["transform-class-properties"]
}
// with options
{
"plugins": [
["transform-class-properties", { "spec": true }]
]
}
babel --plugins transform-class-properties script.js
require("babel-core").transform("code", {
plugins: ["transform-class-properties"]
});
spec
boolean
, defaults to false
.
Class properties are compiled to use Object.defineProperty
. Static fields are now defined even if they are not initialized.