Babel Private Field Plugin
This is a plugin provide private fields in ES6+ class. It's not like ECMAScript Private Fields proposal but automatically transform any field which starts with '_' into a private field.
Usage
npm i babel-plugin-transform-private --save-dev
Config .babelrc
or package.json
Compile results:
Simple class
input:
{ this_x = x; this_y = y; } { return this_x this_y; } { return Math; }
output:
const Point2D = { const $_x$ $_y$ = Symbol"$_x$" Symbol"$_y$"; { this$_x$ = x; this$_y$ = y; } { return this$_x$ this$_y$; } { return Math; } return Point2D;}; ;
Nested class
input:
{ this_inner = { this_x = x; } { return this_x; } } { return this_inner; }
output:
const Outer = { const $_inner$ = Symbol"$_inner$"; { this$_inner$ = { const $_x$ = Symbol"$_x$"; return { this$_x$ = x; } { return this$_x$; } ; }; } { return this$_inner$; } return Outer;}; ;
Protected fields & super
A method or a getter starts with '_' will be transforme to protected field. That means it can be accessed using super
keyword.
input:
const Foo = class { this_x = x; this_y = y; this_zz = x + y; } //protected filed { return this_zz; } const Bar = { superx * 2 y * 3; } { return super_z; //get x*2+y*3 } { return super_zz; //undefined }
output:
const Foo = { const $_x$ $_y$ $_zz$ $_z$ = Symbol"$_x$" Symbol"$_y$" Symbol"$_zz$" Symbol"$_z$"; return class { this$_x$ = x; this$_y$ = y; this$_zz$ = x + y; } { return this$_zz$; } ;}; const Bar = { superx * 2 y * 3; } { return superObject0; } { return superObject0; };