babel-plugin-immutable-record
This plugin is acts as a preprocessor: it takes a mutable class and generates a record with the following properties:
- immutable
- type-safe
update()
to do partial updatestoMap()
to export an untyped Map
It's based Facebook's immutable-js and Flow.
Usage
If you run the plugin on the following input
/* @flow */ ; @ name: string; members: string; active: boolean = true;
it will create a file similar to this (details have been omitted):
/* @flow */ ;; @Base { /* ... */ } get : string /* ... */ get : List<string> /* ... */ get : boolean /* ... */ : MyBand /* ... */ : Map<string any> /* ... */ type MyBandInit = name: string; members: List<string>; active?: boolean ;type MyBandUpdate = name?: string; members?: List<string>; active?: boolean ;
The Flow type checker will prevent:
- missing fields on initalisation
- wrong type for a field
- data for undefined properties
This shows how you could use it:
const band = name: 'The Be Sharps' members: ;console; // prints 'The Be Sharps' const newBand = band;console; // prints 'Barney'
Get Started
(1) Install the plugin:
npm install babel-plugin-immutable-record --save-dev
(2) Add the additional step to your build process, for example in Gulp 4:
var rename = ; gulp; gulp;
NOTE: This is important. The output of the plugin
should be part of the source code, not the transpiled build.
Also, your regular watch task should ignore *.t.js
and
NOT trigger the generate
task - otherwise you created an endless loop.
(3) Finally, you need to define the decorator in your source code:
/* @flow */ : Function { return {};} {}RecordBase = Base; ;
Advanced
Custom decorator
You can pick a custom name for the decorator (default is Record
):
"plugins": ... "babel-plugin-immutable-record" "decorator": "ImmutableContainer"
Obviously, you'll then need to adapt the decorator's source file accordingly.
Header
To insert a custom header at the top of the file (e.g. to disable ESLint):
"plugins": ... "babel-plugin-immutable-record" "header": "my comment"