React and Flux Environment Setup

It did not came to me as easy to start a react project and setting up an environment. This is why I decided to write this blog. The idea here is not to delve deep into react concepts, but instead to help setting up the stadium to play the match. This would come easy to seasoned front end developers but still difficult for one starting react. I would demonstrate how to setup the environment where you have the necessary ingredients to focus on react concept than struggling with the environment.

First: Have Node installed

You should install the node to get started with the environment setup and learning. Browse Node.js and install the appropriate version on your machine. Fifty percent of battle is won right here itself.

Choose your editor

I know visual studio user would love to stick to it, but my experience is that it’s still far being the ideal. I myself used VSCode. You may use other editors from the list below. I would mention only a couple of which are awesome.
  1. VSCode
  2. Webstorm (not free)
  3. Sublime
  4. Atom
Choose your battle ground but the ones above are best. They all come with integrated command terminal or available through plugins.

.editorconfig

This is the file to setup your editor configuration defaults like tabspace, trailing spaces, EOL and many more as per your preferences. This is an optional if you are satisfied with the defaults provided by your choice of editor. An example shown shows the configuration I have for my VSCode.
# editorconfig.org root = true [*] indent_style = tab indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.md] trim_trailing_whitespace = false

Package.json

Instead of going through so many ways to initialize it, I would get straight to the point. Create a folder which would be the root of your application. Then create a file with name package.json in this folder. This file serves as a definition for all framework required by your project. By seeing an example you would be able to guess much out of it. Following is the package.json for react project that uses React, React-Router, Gulp, Flux, ESlint, Bootstrap and Browserify beside some utility tools.
{ "name": "starter", "version": "1.0.0", "description": "React Kickstart", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Manish", "license": "MIT", "dependencies": { "bootstrap": "^3.3.5", "browserify": "^11.0.1", "flux": "^2.0.3", "gulp": "^3.9.0", "gulp-concat": "^2.6.0", "gulp-connect": "^2.2.0", "gulp-eslint": "^0.15.0", "gulp-open": "^1.0.0", "jquery": "^2.1.4", "lodash": "^3.10.0", "object-assign": "^3.0.0", "react": "^0.13.3", "react-router": "^0.13.3", "reactify": "^1.1.1", "toastr": "^2.1.0", "vinyl-source-stream": "^1.1.0" }, "devDependencies": { "gulp-livereload": "^3.8.1" } }

NPM Install

After this use the integrated terminal window, DOS prompt, PowerShell or Bash to run the following command: npm install P.S. Assuming Node.js is installed globally on your machine.
This will install all the framework defined in package.json in your project folder inside node_module. Voila!!! Your project is now setup with the required frameworks. The dependencies are required for production release, while devDependencies are only required for your development environment. Following are the quick description and link for each library mentioned in package.json.
FrameworkDescription
BootstrapFor responsive design.
BrowserifyBrowserify lets you require('modules') in the browser
FluxFlux is an architecture that Facebook uses internally when working with React. It is not a framework or a library. It is simply a new kind of architecture that complements React and the concept of Unidirectional Data Flow.
GulpUsed to automate the build.
Gulp-concatSimply to concat files.
Gulp-connectGulp plugin to run a webserver (with LiveReload).
Gulp-eslintFor linting your codebase (Verify Code Quality)
Gulp-openOpen files and URLs with gulp.
JqueryJavaScript framework required by bootstrap
LodashLodash is a toolkit of Javascript functions that provides clean, performant methods for manipulating objects and collections.
Object-assignFor merging objects. Used by gulp.
ReactReact is a declarative, efficient, and flexible JavaScript library for building user interfaces.
React-routerDelivers navigation elegance to React.
Toastrtoastr is a Javascript library for Gnome / Growl type non-blocking notifications.
Vinyl-source-streamUsed to manage streams in gulp.
Gulp-livereloadHot reload and refresh.

Project Structure explained

The following project structure is simplified keeping in mind the scope of this article. However it is more like what many experts would suggest for the development environment. The project contains all source code inside the folder “src”. All configuration files like pakage.json, eslint.config.json and gulpfile.js resides at the root folder. The “dist” folder is meant for distribution. It is empty in the beginning. The gulp tasks minifies, bundles and copies files in the “dist” folder. Node_modules are the framework that gets installed when “npm install” is executed from the command prompt.

Automation and Build with Gulpfile.json

The gulpfile.js contains the definition of build. It is one of the most preferred and easy to understand tool to automate your build. Each steps of the build process is defined as a task with one task that combines all these sub-tasks into sequence to call each of them and complete the build process. You can further visit the gulp tutorial to take a deep dive. I will provide a quick explanation of each tasks below. Initialization – This is the topmost section that defines variables and plugins that will be used by the gulp tasks. They are assumed to be available to gulp from node modules installed.
"use strict"; var gulp = require('gulp'); var connect = require('gulp-connect'); //Runs a local dev server var open = require('gulp-open'); //Open URL in a web browser var livereload = require('gulp-livereload'); var browserify = require('browserify'); // Bundles JS var reactify = require('reactify'); // Transforms React JSX to JS var source = require('vinyl-source-stream'); // Use conventional text streams with Gulp var concat = require('gulp-concat'); //Concatenates files var lint = require('gulp-eslint'); //Lint JS files, including JSX
Configuration: This section mainly provides gulp with necessary input to define its behavior while automation and execution.
var config = { port:9005, devBaseUrl:'http://localhost', paths:{ html: './src/*.html', js:'./src/**/*.js', images: './src/images/*', css: [ 'node_modules/bootstrap/dist/css/bootstrap.min.css', 'node_modules/bootstrap/dist/css/bootstrap-theme.min.css', 'node_modules/toastr/toastr.scss' ], dist: './dist', mainJs: './src/main.js' } }
The following two tasks defines how gulp would run the build after compilation.
//Start local development server gulp.task('connect', function(){ connect.server({ root:['dist'], port:config.port, base:config.devBaseUrl, liverreload: true }); }); gulp.task('open', ['connect'], function(){ gulp.src('dist/index.html') .pipe(open({ uri: config.devBaseUrl + ':' + config.port + '/' })); });
Html Task – The following task informs gulp to copy source html files to destination and watch for changes during execution. If the source file is changed this task will be automatically called and the browser will be refreshed automatically through “livereload” plugin installed. The livereload plugin is available for chrome as an extension.
gulp.task('html', function() { gulp.src(config.paths.html) .pipe(gulp.dest(config.paths.dist)) .pipe(connect.reload()) .pipe(livereload()); });
JS Task – The following task transforms the React-JS to JavaScript, minifies and bundles all JavaScript to bundle.js. It then copies the bundle.js to “dist/scripts” folder. It further watches and loads the files when changes occur.
gulp.task('js', function() { browserify(config.paths.mainJs) .transform(reactify) .bundle() .on('error', console.error.bind(console)) .pipe(source('bundle.js')) .pipe(gulp.dest(config.paths.dist + '/scripts')) .pipe(connect.reload()) .pipe(livereload()); });
CSS Task – Bundles and minifies the CSS file(s) and copies to the “dist/css” folder.
gulp.task('css', function() { gulp.src(config.paths.css) .pipe(concat('bundle.css')) .pipe(gulp.dest(config.paths.dist + '/css')) .pipe(connect.reload()) .pipe(livereload()); });
Images Task – Copies source images to the “dist/images” folder.
// Migrates images to dist folder // Note that I could even optimize my images here gulp.task('images', function () { gulp.src(config.paths.images) .pipe(gulp.dest(config.paths.dist + '/images')) .pipe(connect.reload()); //publish favicon gulp.src('./src/favicon.ico') .pipe(gulp.dest(config.paths.dist)); });
Lint Task – This task helps gulp to verifying code quality according to the rules defined in eslint.config.json.
gulp.task('lint', function() { return gulp.src(config.paths.js) .pipe(lint({config: 'eslint.config.json'})) .pipe(lint.format()); });
Watch Task – Once the build is executed in Dev Server, this task informs gulp to keep it hot and watch for any changes. If the changes are made, gulp will execute the task to recompile and refresh the content.
gulp.task('watch', function() { livereload.listen(); gulp.watch(config.paths.html, ['html']); gulp.watch(config.paths.js, ['js', 'lint']); });
Combined Default Task – The “default” task is the entry point for gulp that calls all sub-task in sequence defined.
gulp.task('default', ['html', 'js', 'css', 'images', 'lint', 'open', 'watch']);

Eslint.config.json

Gulp uses this file to provide verbose info of code quality during compilation and build.
{ "root": true, "ecmaFeatures": { "jsx": true }, "env": { "browser": true, "node": true, "jquery": true }, "rules": { "quotes": 0, "no-trailing-spaces": 0, "eol-last": 0, "no-unused-vars": 0, "no-underscore-dangle": 0, "no-alert": 0, "no-lone-blocks": 0 }, "globals": { "jQuery": true, "$": true } }

The Hello World of ReactJS

Index.html – The SPA (Single Page Application)

main.js – This is the entry point of ReactJS

homepage.js – A react component

Where to go from here !!

Now you can jump start, concentrating on ReactJS and its features.

Enjoy!!
Manish