babel-plugin-transform-class-bound-properties
This plugin transforms class bound properties with hot reloading supported
Installation
npm
Via npm install --save-dev babel-plugin-transform-class-bound-properties
yarn
Via yarn add --dev babel-plugin-transform-class-bound-properties
Usage
Please make sure transform-class-bound-properties
is listed before transform-class-properties
.
.babelrc
(Recommended)
Via .babelrc
# this will enable the plugin in dev mode only (process.env.NODE_ENV !== 'production')
# this will enable the plugin in both dev mode and production mode
Via CLI
babel --plugins transform-class-bound-properties script.js
Via CLI
Important Note
Editing the .babelrc
won't actually change the setup, unless you start the packager with yarn start --reset-cache
to clean the transform cache.
Why?
Hot module reload (HMR) has been broken for class bound properties in React Native.
The "hot loading" message appears, but the changes don't show up.
;; Component { superprops; thismanualBind = thismanualBind; } { return <View style=flex: 1 paddingTop: 20> <View style=flex: 1 backgroundColor: 'rgba(0, 255, 0, 0.1)'> this </View> <View style=flex: 1 backgroundColor: 'rgba(255, 0, 0, 0.1)'> this </View> </View> ; } { // changes in this "manualBind" method shows up as usual return <View style=flex: 1 justifyContent: 'center' alignItems: 'center'> <Text>Manual reloads fine</Text> </View> ; } { // changes in this "autoBind" method don't show up return <View style=flex: 1 justifyContent: 'center' alignItems: 'center'> <Text>Auto doesn’t hot reload</Text> </View> ; }
How it works?
This plugin transform a bound property into a corresponding unbound class method and a bind statement in constructor
(same as manualBind
method in the sample code above)
{ return thisfield1 } thisfield2 + value asyncBoundFn1 = async { return await thisfield1 } # will be transformed to { thisboundFn1 = thisboundFn1 thisboundFn2 = thisboundFn2 thisasyncBoundFn = thisasyncBoundFn } { return thisfield1 } { return thisfield2 + value } async { return await this }
NOTE:
By default, this plugin transforms bound properties only in DEV mode (process.env.NODE_ENV !== 'production'
).
In production mode (when you build the code for release), as we don't need hot reloading, the plugin doesn't transform anything, so bound properties will be transformed by the plugin babel-plugin-transform-class-properties
as usual.
If you still want to enable this plugin for production mode, please set production
option to true