Home Web Development React.js Essentials

React.js Essentials

By Artemij Fedosejev
books-svg-icon Book
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Installing Powerful Tools for Your Project
About this book
Publication date:
August 2015
Publisher
Packt
Pages
208
ISBN
9781783551620

 

Chapter 1. Installing Powerful Tools for Your Project

Here is a great quote by Charles F. Kettering:

My interest is in the future because I am going to spend the rest of my life there.

This brilliant inventor has left software engineers with the single most important piece of advice way before we even started thinking how to write software. Yet, half a century later, we're still figuring out why we end up with spaghetti code or the "spaghetti mental model".

Have you ever been in a situation where you inherit code from a previous developer and spend weeks trying to understand how everything works because no blueprints were made available, and the pseudo-self-explanatory-code became too hard to debug? Better yet, the project keeps growing and so does its complexity. Making breaking changes is dangerous and no one wants to touch that "ugly" legacy code. Rewriting the whole codebase is way too expensive, so the current one is supported by introducing new bug fixes and patches every day. It is a well-known fact that the cost of maintaining software is way higher than the original cost of developing it.

What does it mean to write software for the future, today? I think it boils down to creating a simple mental model that doesn't change, no matter how big your project becomes over time. When the size of your project grows, the complexity always stays the same. This mental model is your blueprint, and once you understand it you will understand how your whole piece of software works.

If you take a look at modern web development, and in particular, the frontend development, you'll notice that we live in exciting times. Internet companies and individual developers are tackling problems of speed and cost of development versus code and user experience quality.

In 2013, Facebook released React—an open source JavaScript library for building user interfaces. You can read more about it at http://facebook.github.io/react/. In early 2015, Tom Occhino from Facebook summarized what makes React so powerful:

React wraps an imperative API with a declarative one. React's real power lies in how it makes you to write code.

Most of you know that a declarative style of programming results in less code. It tells a computer what to do without specifying how, while an imperative style of programming describes how to do it. JavaScript's call to the DOM API is an example of imperative programming. jQuery is another such example.

Facebook used React in production for years, along with Instagram and other companies. It works for small projects too; here is an example of a shopping list built with React: http://fedosejev.github.io/shopping-list-react. I think React is one of the best JavaScript libraries used for building user interfaces that is available for developers today.

My goal is for you to understand the fundamental principles of React. To achieve this, I will introduce you to one React concept at a time, explain it, and show how you can apply it. Step by step we'll build a real-time web application, raise important questions along the way, and discuss solutions that React provides us with.

We will learn about Flux, which implements a unidirectional flow of data. Together with Flux and React, we'll create a predictable and manageable code base that you will be able to expand by adding new features, without scaling its complexity. The mental model of how your web application works will stay the same no matter how many new features you add later on.

As with any new technology, there are things that work very differently from the way that you're used to. React is not an exception. In fact, some of the core concepts of React might look counter-intuitive, thought provoking, or even a step backward. Don't rush to any conclusions. As you would expect, there are very good reasons behind how React works, and these reasons come from experienced Facebook engineers who build and use React in production in business-critical applications. My advice to you is to keep your mind open while learning React, and I believe that, at the end of this book, these new concepts will settle in and make great sense to you.

Please join me in this journey of learning React and following Charles F. Kettering's advice. Let's take care of our future!

 

Approaching our project


I firmly believe that the best motivation for learning new technology is a project that excites you and that you can't wait to build. As an experienced developer, you've probably already built a number of successful commercial projects that share certain product features, design patterns, and even target audiences. In this book, I want you to build a project that feels like a breath of fresh air. A project which you most likely wouldn't build in your day-to-day work. It has to be a fun endeavor, which not only educates you but also satisfies your curiosity and stretches your imagination. Yet, guessing that you're a busy professional, this project shouldn't be a time consuming, long-term commitment for you either.

Enter Snapterest—a web application that allows you to discover and collect public photos posted on Twitter. Think of it as Pinterest (www.pinterest.com) with the only source of pictures being Twitter. We will implement a fully functional website with the following core functionalities:

  • Receiving and displaying tweets in real time

  • Adding and removing tweets to/from a collection

  • Reviewing collected tweets

  • Exporting a collection of tweets as an HTML snippet that you can share

When you start working on a new project, the very first thing that you do is you get your tools ready. For this project, we will be using a number of tools that you might not be familiar with, so let's discuss what they are, and how you can install and configure them.

If you have any trouble with installing and configuring the tools and modules from this chapter, then go to https://github.com/fedosejev/react-essentials and create a new issue; describe what you're doing and what error message you're getting. I will do my best to help you resolve your issue.

In this book, I'll assume that you're working on a Macintosh or Windows computer. If you're a Unix user, then most likely you will know your package manager very well, and it should be easy enough for you to install the tools that you will learn about in this chapter.

Let's start with the installation of Node.js.

 

Installing Node.js and npm


Node.js (https://nodejs.org) is a platform that allows us to write server-side applications with a client-side language that we're all familiar with—JavaScript. However, the real benefit of Node.js is that it uses an event-driven, non-blocking I/O model, which is perfect for building data-intensive, real-time applications. It means that, with Node.js, we should be able to handle an incoming stream of tweets and process them as soon as they arrive: just what we need for our project.

Let's install Node.js. We'll be using version v0.10.40 because, at the time of writing this book, that's the latest version of Node.js that Jest supports. Jest is a testing framework from Facebook that you'll learn about in Chapter 8, Test Your React Application with Jest.

Go to http://nodejs.org/dist/v0.10.40/ and download the installation package for your OS:

Run it and follow the installation steps that Node.js will prompt you with. Once finished, check whether you have successfully installed Node.js. Open Terminal/Command Prompt, and type the following command:

node -v

The output is as follows:

v0.10.40

Node.js has a very rich ecosystem of modules that is available for us to use. A module is a Node.js application that you can reuse in your own Node.js application. At the time of writing, there are over 120,000 modules. How do you manage such a wide diversity of Node.js modules? Meet npm, a package manager that manages Node.js modules. In fact, npm is shipped together with Node.js, so you've got it installed already. Type in your Terminal/Command Prompt:

npm -v

You should see the following output:

1.4.28

You can learn more about npm at www.npmjs.com. Now we are ready to start with the installation of Node.js applications.

 

Installing Git


In this book, we'll be using Git to install Node.js modules. If you haven't installed Git yet, visit https://git-scm.com/book/en/v2/Getting-Started-Installing-Git and follow the installation instructions for your OS.

 

Getting data from the Twitter Streaming API


The data for our React application will come from Twitter. Twitter has the Streaming API that anyone can plug into and start receiving an endless flow of public tweets in the JSON format.

To start using the Twitter Streaming API, you'll need to perform the following steps:

  1. Create a Twitter account. For this, go to https://twitter.com and sign up; or sign in if you already have an account.

  2. Create a new Twitter App by navigating to https://apps.twitter.com, and click on Create New App. You will need to fill in the Application Details form, agree with the Developer Agreement, and click on Create your Twitter application. Now you should see your application's page. Switch to the Keys and Access Tokens tab.

In the Application Settings section of this page, you'll find two vital pieces of information:

  • Consumer Key (API Key); for example, jqRDrAlKQCbCbu2o4iclpnvem

  • Consumer Secret (API Secret); for example, wJcdogJih7uLpjzcs2JtAvdSyCVlqHIRUWI70aHOAf7E3wWIgD

Take a note of them; we will need them later in this chapter.

Now we need to generate an access token. On the same page, you'll see Your Access Token section that is empty. Click on Create my access token. It creates two pieces of information:

  • Access Token; for example, 12736172-R017ah2pE2OCtmi46IAE2n0z3u2DV6IqsEcPa0THR

  • Access Token Secret; for example, 4RTJJWIezIDcs5VX1PMVZolXGZG7L3Ez7Iz1gMdZucDaM

Take a note of them too. An access token is unique to you and you should not share it with anyone. Keep it private.

Now we have everything that we need to start using Twitter's Streaming API.

 

Filtering data with Snapkite Engine


The amount of tweets that you'll receive via the Twitter Streaming API is more than you can ever consume, so we need to find a way to filter that stream of data into a meaningful set of tweets that we can display and interact with. I recommend that you take a quick look at the Twitter Streaming API documentation at https://dev.twitter.com/streaming, and in particular, take a look at this page that describes the way you can filter an incoming stream at https://dev.twitter.com/streaming/reference/post/statuses/filter. You'll notice that Twitter provides very few filters that we can apply, so we need to find a way to filter that stream of data even further.

Luckily, there is a Node.js application just for this. It's called Snapkite Engine. It connects to the Twitter Streaming API, filters it using the available filters and according to the rules that you define, and outputs the filtered tweets to a web socket connection. Our proposed React application can listen to the events on that socket connection and process tweets as they arrive.

Let's install Snapkite Engine.

First, you need to clone the Snapkite Engine repository. Cloning means that you're copying the source code from a GitHub server to your local directory. In this book, I'll assume that your local directory is your home directory. Open Terminal/Command Prompt and type the following commands:

cd ~
git clone https://github.com/snapkite/snapkite-engine.git

This should create the ~/snapkite-engine/ folder. We're now going to install all the other node modules that snapkite-engine depends on. One of them is the node-gyp module. Depending on what platform you're using, Unix or Windows, you will need to install other tools that are listed on this web page: https://github.com/TooTallNate/node-gyp#installation.

Once you install them, you're ready to install the node-gyp module:

npm install --global node-gyp

Now navigate to the ~/snapkite-engine directory:

cd snapkite-engine/

Then run the following command:

npm install

This command will install the Node.js modules that Snapkite Engine depends on. Now let's configure Snapkite Engine. Assuming that you're in the ~/snapkite-engine/ directory, copy the ./example.config.json file to ./config.json by running the following command:

cp example.config.json config.json

Or if you're using Windows, run this command:

copy example.config.json config.json

Open config.json in your favorite text editor. We will now edit the configuration properties. Let's start with trackKeywords. This is where we will tell what keywords we want to track. If we want to track the keyword "my", then set it as follows:

"trackKeywords": "my"

Next, we need to set our Twitter Streaming API keys. Set consumerKey, consumerSecret, accessTokenKey, and accessTokenSecret to the keys you saved when you created your Twitter App. Other properties can be set to their defaults. If you're curious to learn about what they are, check out the Snapkite Engine documentation at https://github.com/snapkite/snapkite-engine.

Our next step is to install Snapkite Filters. Snapkite Filter is a Node.js module that validates tweets according to a set of rules. There are a number of Snapkite Filters out there, and we can use any combination of them to filter our stream of tweets as we like. You can find a list of all the available Snapkite Filters at https://github.com/snapkite/snapkite-filters.

In our application, we'll use the following Snapkite Filters:

Let's install them. Navigate to the ~/snapkite-engine/filters/ directory:

cd ~/snapkite-engine/filters/

Then clone all Snapkite Filters by running these commands:

git clone https://github.com/snapkite/snapkite-filter-is-possibly-sensitive.git
git clone https://github.com/snapkite/snapkite-filter-has-mobile-photo.git
git clone https://github.com/snapkite/snapkite-filter-is-retweet.git
git clone https://github.com/snapkite/snapkite-filter-has-text.git

The next step is to configure them. In order to do so, you need to create a configuration file for each Snapkite Filter in JSON format and define some properties in it. Luckily, each Snapkite Filter comes with an example configuration file that we can duplicate and edit as needed. Assuming that you're in the ~/snapkite-engine/filters/ directory, run the following commands (use copy and replace the forward slashes with the backward slashes on Windows):

cp snapkite-filter-is-possibly-sensitive/example.config.json snapkite-filter-is-possibly-sensitive/config.json
cp snapkite-filter-has-mobile-photo/example.config.json snapkite-filter-has-mobile-photo/config.json
cp snapkite-filter-is-retweet/example.config.json snapkite-filter-is-retweet/config.json
cp snapkite-filter-has-text/example.config.json snapkite-filter-has-text/config.json

We don't need to change any of the default settings in these config.json files, as they're already configured to fit our purposes.

Finally, we need to tell Snapkite Engine which Snapkite Filters it should use. Open the ~/snapkite-engine/config.json file in a text editor and look for this:

"filters": []

Now replace that with the following:

"filters": [
  "snapkite-filter-is-possibly-sensitive",
  "snapkite-filter-has-mobile-photo",
  "snapkite-filter-is-retweet",
  "snapkite-filter-has-text"
]

Well done! You've successfully installed Snapkite Engine with a number of Snapkite Filters. Now let's check if we can run it. Navigate to ~/snapkite-engine/ and run the following command:

npm start

You should see no error messages, but if you do and you're not sure how to fix them, then please go to https://github.com/fedosejev/react-essentials/issues, create a new issue and copy/paste the error message that you get.

Next, let's set up our project's structure.

 

Creating the project structure


It's time to create our project structure. Organizing source files may sound like a simple task, but a well-thought-out project structure organization helps us understand the underlying architecture of our application. You'll see an example of this later in this book, when we'll talk about the Flux application architecture. Let's start by creating our root project directory named snapterest inside your home directory ~/snapterest/.

Then, inside it, we will create two other directories:

  • ~/snapterest/source/: Here we'll store our source JavaScript files

  • ~/snapterest/build/: Here we'll put compiled JavaScript files and an HTML file.

Now, inside ~/snapterest/source/, create the components/ folder so that your project structure would look like this:

  • ~/snapterest/source/components/

  • ~/snapterest/build/

Now, when we have our fundamental project structure ready, let's start populating it with our application files. First, we need to create our main application file app.js in the ~/snapterest/source/ directory. This file will be the entry point to our application, ~/snapterest/source/app.js.

Leave it empty for now, as we have a more pressing matter to discuss.

 

Creating package.json


Have you ever heard of DRY before? It stands for Don't Repeat Yourself, and it promotes one of the core principles in software development—code reuse. The best code is the one that you don't need to write. In fact, one of our goals in this project is to write as little code as possible. You might not realize this just yet, but React helps us achieve this goal. Not only does it save us time, but if we also decide to maintain and improve our project in future, it will save us even more time in the long run.

When it comes to not writing code, we can apply the following strategies:

  • Writing our code in a declarative programming style

  • Reusing the code written by someone else

In this project, we'll be using both these techniques. The first one is covered by React itself. React leaves us no choice but to write our JavaScript code in a declarative style. This means that instead of telling our web browser how to do what we want (like we do in jQuery), we just tell it what we want it to do and the how part is explained by React. That's a win for us.

Node.js and npm cover the second technique. I've mentioned earlier in this chapter that there are a hundred thousand different Node.js applications available for us to use. This means that most likely someone has already implemented the functionality that our application depends on.

The question is how do you know from where to get all these Node.js applications that we want to reuse. We can install them via the npm install <package-name> command. In the npm context, a Node.js application is called a package, and each npm package has a package.json file that describes the metadata associated with that package. You can learn more about what fields are stored in package.json at https://docs.npmjs.com/files/package.json.

Before we install our dependency packages, we will initialize a package for our own project. Normally, package.json is only required when you want to submit your package to the npm registry so that others can reuse your Node.js application. We're not going to build a Node.js application, and we're not going to submit our project to npm. Remember that package.json is technically only a metadata file that the npm command understands, and as such, we can use it to store a list of dependencies that our application requires. Once we store a list of dependencies in package.json, we can easily install them anytime with the npm install command; npm will figure out from where to get them automatically.

How do we create the package.json file for our own application? Luckily, npm comes with an interactive tool that asks us a bunch of questions and then, based on our answers, creates package.json for our project.

Make sure that you're located in the ~/snapterest/ directory. On the Terminal/Command Prompt run the following command:

npm init

The first question it will ask you is your package name. It will suggest a default name that is the directory name you're located in. It should suggest name: (snapterest) in our case. Press Enter to accept the proposed default name (snapterest). The next question is the version of your package, that is, version: (1.0.0). Press Enter. These two would be the most important fields if we were planning to submit our package to npm for others to reuse. Because we're not going to submit it to npm, we can confidently accept defaults for all the questions that we are asked. Keep pressing Enter until npm init completes its execution and exits. Then, if you go to your ~/snapterest/ directory, you will find a new file there, package.json.

Now we're ready to install other Node.js applications that we're going to reuse. An application that is built of multiple individual applications is called modular, whereas individual applications are called modules. This is what we'll call our Node.js dependencies from now on—Node.js modules.

 

Reusing Node.js modules


As I mentioned earlier, there will be a step in our development process called building. During this step, our build script will take our source files and all our Node.js dependency packages, and transform them into a single file that web browsers can successfully execute. The most important part of this building process is called packaging. But what do we need to package and why? Let's think about it. I briefly mentioned earlier that we're not creating a Node.js application, but yet we're talking about reusing Node.js modules. Does this mean that we'll be reusing Node.js modules in a non-Node.js application? Is that even possible? Turns out, there is a way of doing that.

Browserify is a tool used for bundling all your dependency files together in such a way that you can reuse Node.js modules in client-side JavaScript applications. You can learn more about Browserify at http://browserify.org. To install Browserify, run the following command from inside the ~/snapterest/ directory:

npm install --save-dev browserify

Notice the --save-dev flag. It tells npm to add Browserify to our package.json as a development dependency. Adding a module name to our package.json file as a dependency allows us to record what dependencies we're using, and we can easily install them later with the npm install command, if needed. There is a distinction between dependencies that are required to run your application and the ones that are required to develop your application. Browserify is used at build time, and not at runtime, so it's a development dependency. Hence the use of the --save-dev flag. If you check the content of your package.json file now, you'll see this:

"devDependencies": {
  "browserify": "^11.0.1"
}

Notice that npm created a new folder in your ~/snapterest/ directory called node_modules. This is the place where it puts all your local dependency modules.

Congrats on installing your first Node.js module! Browserify will allow us to use Node.js modules in our client-side JavaScript applications. It will be a part of our build process. Speaking of which, I think it's a good time to introduce you to our build tools.

 

Building with Gulp.js


Today, any modern client-side application represents a mix of many concerns that are addressed individually by various technologies. Addressing each concern individually simplifies the overall process of managing the project's complexity. The downside of this approach is that at some point in your project, you need to put together all the individual parts into one coherent application. Just like the robots in an automotive factory that assemble cars from individual parts, developers have something called build-tools that assemble their projects from individual modules. This process is called the build process and, depending on the size and complexity of your project, it can take anywhere from milliseconds to hours to build.

The Node.js ecosystem has a great tool for automating our build process, Gulp.js. You can learn more about Gulp.js at http://gulpjs.com. Let's install it:

npm install --save-dev gulp

Once again, we need this module for developing, but not running, our application. Only this time we also want to install our module globally:

npm install --global gulp

This would allow us to run it from the Terminal/Command Prompt. To check whether you have Gulp.js installed, run this command:

gulp

You should see the following output:

No gulpfile found

This means that you have successfully installed Gulp.js.

What is this gulpfile anyway? It's a file where we describe our build process. Create gulpfile.js in your ~/snapterest/ directory and add the following content to it:

var gulp = require('gulp');

gulp.task('default', function() {
  console.log('I am about to learn the essentials of React.js');
});

Now if you run the gulp command, you will see output that looks like this:

Using gulpfile ~/snapterest/gulpfile.js
Starting 'default'...
I am about to learn the essentials of React.js
Finished 'default' after 62 μs

By default, when you run gulp, it executes a task called (no surprise here) default. Well done! You now have a working Gulp.js build system. Let's create a task that will package our source and dependency modules using Browserify.

Replace the content of your gulpfile.js with the following code:

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('default', function () {
  return browserify('./source/app.js')
        .transform(babelify)
        .bundle()
        .pipe(source('snapterest.js'))
        .pipe(gulp.dest('./build/'));
});

As you can see, we will use the require() function to import three new dependency modules: browserify, babelify, and vinyl-source-stream. We have already installed the browserify module, so now let's install the babelify module:

npm install --save-dev babelify

The babelify module allows us to write the JSX syntax that we'll introduce in the next chapter.

Why do we need the vinyl-source-stream module? In a nutshell, it allows us to use Browserify and Gulp together. If you're interested in more details on why this works, go to https://www.npmjs.com/package/vinyl-source-stream. Let's install our vinyl-source-stream dependency module:

npm install --save-dev vinyl-source-stream

Now we're ready to test our default task. Run this command:

gulp

The output should look something like this:

Using gulpfile ~/snapterest/gulpfile.js
Starting 'default'...
Finished 'default' after 48 ms

More importantly, if you check your project's ~/snapterest/build/ directory, you'll notice that it now has the snapterest.js file with some code already inside it—that's our (empty) JavaScript application with some Node.js modules that are ready to run in a web browser!

 

Creating a web page


If you're starving for some React goodness, then I have great news for you! We're almost there. All that's left to do is to create index.html with a link to our snapterest.js script.

Create the index.html file in the ~/snapterest/build/ directory. Add the following HTML markup to it:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge, chrome=1" />
    <title>Snapterest</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  </head>
  <body>
    <div id="react-application">
      I am about to learn the essentials of React.js.
    </div>
    <script src="./snapterest.js"></script>
  </body>
</html>

Open ~/snapterest/build/index.html in a web browser. You should see the following text: I am about to learn the essentials of React.js. That's right, we have finished setting up our project, and it's time to get to know React!

 

Summary


In this chapter, we learned why we should use React to build user interfaces for modern web applications. Then, we discussed the project that we'll be building in this book. Finally, we installed all the right tools and created the project's structure. In the next chapter, we'll install React, take a closer look at how React works, and create our first React Element.

About the Author
  • Artemij Fedosejev

    Artemij Fedosejev is a technical lead living in London, United Kingdom. He is a self-taught web developer who has been a web developer since the early 2000s. Artemij earned his BSc in computer science from University College Cork, Ireland. He participated in the IGNITE Graduate Business Innovation Programme, where he built and launched a website that received the Most Innovative Project award. Artemij has played a key role in creating frontend architecture using React.js and Flux for various websites. Artemij created a number of open source projects, including Snapkite Engine, Snapkite Stream Client, and other projects.

    Browse publications by this author
Latest Reviews (29 reviews total)
Great introduction to ReactJS! A must read for all beginners out there!
See other review ..........
React.js Essentials
Unlock this book and the full library FREE for 7 days
Start now