Babel plugin for extracting react native inline styles to StyleSheet.create
Description | Install | Usage | How it works ?
Description
This babel plugin will extract any inline styles to the StyleSheet.create
object in a react native application.
StyleSheet.create
?
Why it's important to have styles inside The React Native StyleSheet
creates immutable stylesheet references.
The style objects passed into the create()
method are freezed and an ID is assigned to each one of them.
This will avoid creating a new style objecct every render pass.
It also allows to send the style only once through the bridge.
Install
npm:
npm install --save-dev babel-plugin-rn-extract-style
yarn:
yarn add babel-plugin-rn-extract-style --dev
Usage
babel.config.js
moduleexports = plugins: 'rn-extract-style'
node_modules
Include By default files from the node_module
are ignored if, you wish to include those you have to specify the includeNodeModules: true
option:
babel.config.js
moduleexports = plugins: './plugin.js' includeNodeModules: true
How it works
The plugin parses the contents of each JSX Element and extract the inline styles, generates an uniquie uid for it and appends it to the StyleSheet.create
object found in the file. In case of a missing StyleSheet.create
instance it generates a new one.
in:
const Component = <View style= height: 500 width: '100%' backgroundColor: '#6c5b7b' > <View style= height: 200 > <Text style= fontSize: 12 >Lorem ipsum</Text> </View> </View>
out:
const Component = <View style=babelGeneratedStylesView_style> <View style=babelGeneratedStylesView_style1> <Text style=babelGeneratedStylesText_style2>Lorem ipsum</Text> </View> </View> const babelGeneratedStyles = StyleSheet