This recipe gets you set up with React, including precompilation of JSX into JavaScript, integrated with LiveReload.
Install gulp-babel, and the required presets for transforming JSX templates into vanilla JavaScript:
$ npm install --save-dev gulp-babel babel-preset-es2015 babel-preset-react
Install React itself as a Bower component:
$ bower install --save react
Run the wiredep task to insert a script tag into your app/index.html:
$ gulp wiredep
This task preprocesses .jsx files into pure JavaScript and outputs them in .tmp/scripts.
gulp.task('templates', () => {
return gulp.src('app/scripts/**/*.jsx')
.pipe($.sourcemaps.init())
.pipe($.babel({
presets: ['es2015','react']
}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/scripts'));
});gulp.task('html', ['styles', 'templates'], () => {
...gulp.task('serve', ['styles', 'templates', 'fonts'], () => {
...- The
servedependency means the generated.jsfiles will be ready in.tmp/scriptsbefore the server starts up - The
htmldependency means your JSX also gets compiled as part of thegulp buildsequence – before thehtmltask starts, so that the.jsfiles are generated in time for gulp-useref to concatenate them.
Edit your serve task so that (a) editing a .jsx file triggers the templates task, and (b) the browser is refreshed whenever a .js file is generated in .tmp/scripts:
gulp.task('serve', ['styles', 'templates', 'fonts'], () => {
...
gulp.watch([
'app/*.html',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
+ '.tmp/scripts/**/*.js',
'app/images/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles', reload]);
+ gulp.watch('app/scripts/**/*.jsx', ['templates', reload]);
gulp.watch('bower.json', ['wiredep', 'fonts', reload]);
});-
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.