Create React-Native Apps with CoffeeScript
Being a web developer I really like React-Native to create native apps, while leveraging my existing Javascript knowledge.
More importantly one can actually use the same code for Android and iOS!
However I am a big fan of using CoffeeScript over Javascript for its nice syntax. So I thought why not just write it in CoffeeScript:
React = require "react-native"
{ AppRegistry, Text, StyleSheet } = ReactApplication = React.createClass
render: ->
React.createElement Text, style: styles.heading, "Hello World"styles = StyleSheet.create
heading:
fontSize: 42
textAlign: 'center'
marginTop: 50AppRegistry.registerComponent “Example”, () -> Application
Now compile it to JS and run the app:
coffee -cb index.ios.coffee
But I want JSX!
Using React.createElement for everything isn’t that nice. The plain CoffeeScript compiler can’t understand JSX, but cjsx can help here!
So I changed my code to use JSX:
React = require "react-native"
{ AppRegistry, Text, StyleSheet } = ReactApplication = React.createClass
render: -> <Text style={styles.heading}>Hello World</Text>styles = StyleSheet.create
heading:
fontSize: 42
textAlign: 'center'
marginTop: 50AppRegistry.registerComponent “Example”, () -> Application
I installed cjsx and compiled my code again: (see the compiled result)
npm install -g coffee-react
cjsx -cb index.ios.coffee
Et voilà it compiles and runs!
cjsx supports the same options as the CoffeeScript compiler. To avoid calling the command on every code change just add the -w option and it watches for file changes.
If you want to use a build tool instead, there are also plugins for gulp and grunt.