This recipe gets you set up with React, including precompilation of JSX into JavaScript, integrated with LiveReload.
Install gulp-react, a gulp plugin for transforming JSX templates into real JavaScript:
$ npm install --save-dev gulp-reactInstall React itself as a bower component:
$ bower install --save reactRun the wiredep task to insert a script tag into your app/index.html:
$ gulp wiredep...or if you don't want to use wiredep, just add the script tag manually:
<script src="../bower_components/react/react.js"></script>This task preprocesses .jsx files into pure JavaScript and outputs them in .tmp/scripts.
gulp.task('jsx', function () {
return gulp.src('app/scripts/**/*.jsx')
.pipe($.react())
.pipe(gulp.dest('.tmp/scripts'));
});gulp.task('serve', ['connect', 'styles', 'jsx'], function () {
...gulp.task('html', ['styles', 'jsx'], function () {
...
- The
servedependency means the generated.jsfiles will be ready in.tmp/scriptsbefore the server starts up (when running either$ gulp serveor$ gulp watch)- The
htmldependency means your JSX also gets compiled as part of the$ gulp buildsequence – before thehtmltask starts, so that the.jsfiles are generated in time for gulp-useref to concatenate them.
Edit your watch task so that (a) editing a .jsx file triggers the jsx task, and (b) the LiveReload server is notified whenever a .js file is generated in .tmp/scripts:
gulp.task('watch', ['connect', 'serve'], function () {
gulp.watch([
'app/*.html',
'.tmp/styles/**/*.css',
- 'app/scripts/**/*.js',
+ '{.tmp,app}/scripts/**/*.js',
'app/images/**/*'
]).on('change', function (file) {
server.changed(file.path);
});
gulp.watch('app/styles/**/*.scss', ['styles']);
+ gulp.watch('app/scripts/**/*.jsx', ['jsx']);
gulp.watch('app/images/**/*', ['images']);
gulp.watch('bower.json', ['wiredep']);
});-
Put your
.jsxfiles anywhere inapp/scripts, but include them in your HTML as if they're.jsfiles – e.g. forapp/scripts/foo.jsx, use<script src="scripts/foo.js"></script>. -
It's fine to have a mixture of
.jsand.jsxfiles in yourapp/scripts.