ReactJS with Babel and Gulp
This is a very short post explaining how to compile JSX files with Babel.
First of all we have to clarify that the old method ( react-tools ) is deprecated, for this reason we have to use Babel and Gulp.
My example is very easy and is a “Getting Start”, you can upgrade as you want.
First we have to install NPM.
After we have to install Gulp as a global package
npm install -g gulp
Now is time to download React here
Create a folder project, for example, BabelReact
Copy the react build folder into BabelReact folder ( your project folder )
Into the BabelReact folder create an index.html file and paste the following code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello Cingusoft React!</title>
<script src="build/react.js"></script>
</head>
<body>
<div id="example"></div>
<script src="dist/main.js"></script>
</body>
</html>
Into the BabelReact folder create an src folder
Go to the src folder and create a helloworld.js file and add this example code
React.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
Now is time to configure Gulp and Babel
Go to the root folder ( BabelReact ) and create the gulpfile.js file and paste the following code
var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var concat = require("gulp-concat");
gulp.task("default", function () {
return gulp.src("src/**/*.js")
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(concat("main.js"))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest("build"));
});
Before start using Gulp we have to install some dependencies
npm install — save-dev gulp-babel
npm install — save-dev gulp-sourcemaps
npm install — save-dev gulp-concat
Now into the root folder you can start gulp
:> gulp
That’s all.