1 | # babel-plugin-transform-class-properties
|
2 |
|
3 | > This plugin transforms es2015 static class properties as well as properties declared with the es2016 property initializer syntax.
|
4 |
|
5 | ## Example
|
6 |
|
7 | Below is a class with four class properties which will be transformed.
|
8 |
|
9 | ```js
|
10 | class Bork {
|
11 | //Property initializer syntax
|
12 | instanceProperty = "bork";
|
13 | boundFunction = () => {
|
14 | return this.instanceProperty;
|
15 | }
|
16 |
|
17 | //Static class properties
|
18 | static staticProperty = "babelIsCool";
|
19 | static staticFunction = function() {
|
20 | return Bork.staticProperty;
|
21 | }
|
22 | }
|
23 |
|
24 | let myBork = new Bork;
|
25 |
|
26 | //Property initializers are not on the prototype.
|
27 | console.log(myBork.prototype.boundFunction); // > undefined
|
28 |
|
29 | //Bound functions are bound to the class instance.
|
30 | console.log(myBork.boundFunction.call(undefined)); // > "bork"
|
31 |
|
32 | //Static function exists on the class.
|
33 | console.log(Bork.staticFunction()); // > "babelIsCool"
|
34 | ```
|
35 |
|
36 |
|
37 | ## Installation
|
38 |
|
39 | ```sh
|
40 | npm install --save-dev babel-plugin-transform-class-properties
|
41 | ```
|
42 |
|
43 | ## Usage
|
44 |
|
45 | ### Via `.babelrc` (Recommended)
|
46 |
|
47 | **.babelrc**
|
48 |
|
49 | ```json
|
50 | // without options
|
51 | {
|
52 | "plugins": ["transform-class-properties"]
|
53 | }
|
54 |
|
55 | // with options
|
56 | {
|
57 | "plugins": [
|
58 | ["transform-class-properties", { "spec": true }]
|
59 | ]
|
60 | }
|
61 | ```
|
62 |
|
63 | ### Via CLI
|
64 |
|
65 | ```sh
|
66 | babel --plugins transform-class-properties script.js
|
67 | ```
|
68 |
|
69 | ### Via Node API
|
70 |
|
71 | ```javascript
|
72 | require("babel-core").transform("code", {
|
73 | plugins: ["transform-class-properties"]
|
74 | });
|
75 | ```
|
76 |
|
77 | ## Options
|
78 |
|
79 | ### `spec`
|
80 |
|
81 | `boolean`, defaults to `false`.
|
82 |
|
83 | Class properties are compiled to use `Object.defineProperty`. Static fields are now defined even if they are not initialized.
|
84 |
|
85 | ## References
|
86 |
|
87 | * [Proposal: ES Class Fields & Static Properties](https://github.com/jeffmo/es-class-static-properties-and-fields)
|