Introducing Reactjs in Google Offline First Project by Udacity

Ishank Sharma
3 min readMar 11, 2018

Well, I recently applied to the Google Re-Skilling Program for scholarship and got selected ,But to my horror saw the course had an issue it was made on a stack that was about an year old .Just type Gulp.js in Google.Since I also started working on React and was very much impressed by the build pipeline it had along with Webpack. I wanted to extend this project and work on it for practice as it had been superbly configured ,I thought to myself Lets add react.

Obviously an Evil thought.

Well turns out its really easy to add react to anything , if you know what you’re doing

Step 1 PACKAGE INSTALLATION

You’ll need these commands

-> npm install --save react react-dom
-> npm install --save-dev babel-loader babel-preset-env babel-preset-es2015 babel-preset-es2017 babel-preset-es2018
-> npm install --save-dev webpack webpack-cli

Step 2 Adding Config Files

You need One additional config files

  • webpack.config.js

Put them in your project folder (the outer most one)

This file is what tells webpack how and where to compile the file to .
We’ll call the react output script reactbundle.js
To run webpack just add this in your Package.json
..."scripts":{

webpack: "webpack-cli --watch"
}...

Now go to command line and run

npm run webpack

This will output reactbundle.js in the directory specified in webpack.config.js.
“/public/js/reactbundle.js”

Step 3 Adding “reactbundle.js” to the html page

React works by targeting a HTML DOM element and mounting a react element on top of it.

If you’re here for adding react to your normal project just adding
<script src=”path/to/public/js/reactbundle.js”></script> would work.

However , in our case it gets a bit tricky since we have a static JS assests serving pipeline already enabled, i’ts best to use the current one.
First of all add following to your /templates/index.hbs

Now open /server/server.js ,find the class declaration for the Server

export default class Server {
…..
this._app.use(‘/avatars’, express.static(‘../public/avatars’, staticOptions));
//Add the following line
this._app.use(‘/reactbundle.js’, (req, res) => res.sendFile(path.resolve(‘../public/reactbundle.js’), staticOptions));
//
this._app.use(‘/sw.js’, (req, res) => res.sendFile(path.resolve(‘../public/sw.js’), staticOptions));

Now open /gulpfile.js ,and find the jsBundles variable and add the following line,

‘reactbundle.js’: createBundle(‘./public/js/reactbundle.js’)

Restart the server and voila , you can see a hello react html in the layout

YAY!

Thanks for suffering through till here, If you enjoyed the article do let me know and constructive criticism is always welcome.

--

--