Package Exports
- @babel/plugin-transform-classes
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@babel/plugin-transform-classes) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@babel/plugin-transform-classes
Compile ES2015 classes to ES5
Caveats
Built-in classes such as Date
, Array
, DOM
etc cannot be properly subclassed
due to limitations in ES5 (for the classes plugin).
You can try to use babel-plugin-transform-builtin-extend based on Object.setPrototypeOf
and Reflect.construct
, but it also has some limitations.
Examples
In
class Test {
constructor(name) {
this.name = name;
}
logger () {
console.log("Hello", this.name);
}
}
Out
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function () {
function Test(name) {
_classCallCheck(this, Test);
this.name = name;
}
Test.prototype.logger = function logger() {
console.log("Hello", this.name);
};
return Test;
}();
Installation
npm install --save-dev @babel/plugin-transform-classes
Usage
Via .babelrc
(Recommended)
.babelrc
// without options
{
"plugins": ["@babel/transform-classes"]
}
// with options
{
"plugins": [
["@babel/transform-classes", {
"loose": true
}]
]
}
Via CLI
babel --plugins @babel/transform-classes script.js
Via Node API
require("@babel/core").transform("code", {
plugins: ["@babel/transform-classes"]
});
Options
loose
boolean
, defaults to false
.
Method enumerability
Please note that in loose mode class methods are enumerable. This is not in line with the spec and you may run into issues.
Method assignment
Under loose mode, methods are defined on the class prototype with simple assignments instead of being defined. This can result in the following not working:
class Foo {
set bar() {
throw new Error("foo!");
}
}
class Bar extends Foo {
bar() {
// will throw an error when this method is defined
}
}
When Bar.prototype.foo
is defined it triggers the setter on Foo
. This is a
case that is very unlikely to appear in production code however it's something
to keep in mind.