Setup React App Using Node.js, Webpack And TypeScript

React is one of the leading technologies that is used to create single page applications(SPA). Some others are Angular and Vue.js. In this article we will  learn how to set up a React project using Webpack, Node.js and Typescript.

React
If you are new to React or want to get some basic knowledge, then you can refer to the below URL.

 

Before staring the setup process it will be better to have a  basic intro about terminologies that we are going use. Let’s read about them one by one.

React

React is a JavaScript library for building the user interface. React uses the component to divide the whole user interface into small sections and at each component contains its own property and state. If you are using the Redux in React app then the application will have a common state instead of the individual state for each component. React makes it easy to create UI interface and update the particular section of UI when any data or state is changed for that component. You can find more about the React here.

 

Node.js

Node.js is an open-source , cross platform JavaScript run time environment for executing the JavaScript code at server side. Node.js built on chrome V8 JavaScript engine. Node.js is used to create Real time, web application and command line applications. Find out more about the Node.js here.

 

Webpack

Webpack is module bundler that takes your modules with dependencies and generates static assets representing those modules. If we are working with a website, then it is possible that it contains a large number of JS and CSS files. Webpack not only bundles our resources like JS and CSS but it also transforms them and allows us to write our code in ES6 (ECMA Script 6). In current time, all the technologies like Angular2, React etc. use ES6 for the development. But every browser doesn’t necessarily understand the ES6, so Webpack compiles the code into ES5 such that the browser can understand the code. If you are new to Webpack or want to get some basic stuff about the Webpack then refer to the below link.

 

TypeScript

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. TypeScript make it easy to organize our code and provides Object Oriented Programming. At compile time TypeScript checks for the error and generates the error if it finds any kind of syntax or type error otherwise it converts the TypeScript code into JavaScript. Find more about TypeScript here.

 

After getting the brief intro, I know we can start to set up our project. Let’s set up a React application from scratch.

Step 1 Create package.json file

First of all create a folder in any directory and name this folder “ReactSetup;” or you can give any name that you want. Now open this folder into any IDE. Here I am using the “Visual Studio Code” If you are using the VS Code then go to “view” menu and open the “Integrated Terminal” window. If you are using another IDE then open a command prompt for following project directory and run the “npm init” command. When you run this command it will ask some details to fill in and generates a package.json file for the project. This file contains information about packages that we install and also contains that script for several commands.

React

Step 2 Setup Node Server

Now run the below command into terminal window.

npm install --save express

React

Above command installs the express packages for the project. Express is a Node.js web application framework that provides a robust set of features to set up and run the web and mobile applications. After installing the package now create a “server.js” in root directory of the application and paste the following code into this file.

  1. var express=require('express');  
  2. var path=require('path');  
  3. var app=express();  
  4. var port=5000;  
  5. app.get('/',function(req,res){  
  6.     res.send('<html><body><h2>Congrts!!! Server Configured</h2</body></html>');  
  7. });  
  8. app.get('/api',function(req,res){  
  9.     res.send('<p>This is a api Data</p>');  
  10. });  
  11. app.listen(port,function(error){  
  12.     if(error) {  
  13.         console.log(error);  
  14.     } else {  
  15.         console.log("Application running on port: "+port);  
  16.     }  
  17. })  

Save all the changes and run the “node server.js” command into the terminal. This command runs over applications at the 5000 port, now open the browser and type the http://localhost:5000/ URL and press enter. If you get the below output that means your node.js server is configured successfully.

React
If you want to make any changes into “server.js” file then after making the changes you have to stop the current execution of node.js server and restart the node.js server using the “node server.js” command, so this process is very time consuming. To overcome this issue we can use the “nodemon”. Actually “nodemon” monitors the utility for any changes if any changes are done then it will restart your server automatically. If “nodemon” is not installed in your machine then you can install “nodemon” using the “npm install -g nodemon” command. This command installs the “nodemon” packages globally. After installing the nodemon now run the “nodemon server.js” command in terminal. This command runs the node server and also monitors the changes into code. When you make any change into “Server.js” file, you will find that nodemon restarts the “node” server and you don’t need to restart the node server again.


React

Let’s make some modification into our code. So far we have directly run either “node server.js” or “nodemon server.js” command into command terminal. Instead of this we can create a script in “package.json” file that will run this command for us. So add the below line of code into “scripts” section of package.json file.

"node":"nodemon server.js"

React

After adding the above script now we run “npm run node” command in terminal and this command runs the “nodemon server.js” script for us.

Step 3 Setup Client App:

So far we configured the “node” server that provides the back end functionality for our application. Now we setup the client side(front end) for our application. First of all we create a React app using the webpack and later we configure this React app(client app) to our node server that we configured.

Now run “npm install react react-dom --save” command; this command installs the react and react-dom packages into our project.

React

Now we install the webpack related dependencies, for this run the “npm install --save-dev webpack webpack-dev-server” command.

React

We install the webpack packages as “devDependencies” because we need the webpack only for development and don’t need it at production time.

React uses the JSX(JavaScript Syntax XML) to create the component. JSX provide the XML syntax in JavaScript, we can create a React app with the JSX but JSX makes the React more elegant. We can use the JSX in React application but browser doesn’t understand the JSX format, so we need a compiler that can convert the JSX syntax to plane JavaScript .In React we use the JSX and write the JavaScript code into ES6 format and all the browsers don’t understand the ES6 format. So we need an intermediary that can convert the ES6 code to ES5 code. So babel runs the ES6 code in our browser. So run the below command to install all required babel packages.

npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-react-hmre babel-preset-stage-2.

React

Here babel-core and babel-loader are main dependencies and other dependencies provide the set of rules to babel for the react development.

Add index.html file

After installing all the required packages now add index.html file in root directory of the application and paste following code into this file.

  1. <html>  
  2.     <head>  
  3.         <title>  
  4.             MEAN Stack  
  5.         </title>  
  6.     </head>  
  7.     <body>  
  8.         <div id="app"></div>  
  9.         <script src='bundle.js'></script>   
  10.     </body>  
  11. </html>  

In the above lines of code we write simple html code and add path for “bundle.js” file, that will be generated by the webpack and contains the React code into JavaScript format.

Add webpack.config.js file

Add a file in root directory of the project and name this file as “webpack.config.js”, this file provides the configuration code for the webpack. After creating this file now paste the following code into this file.

  1. var webpack=require('webpack');  
  2. var path=require("path");    
  3. var srcPath=path.resolve(__dirname,"client");    
  4. var distPath=path.resolve(__dirname,"public");   
  5. var config={  
  6.     devtool:'source-map',  
  7.     entry:[  
  8.         srcPath+"/app.js"  
  9.     ],  
  10.     output:{    
  11.         path:distPath,    
  12.         publicPath: '/',  
  13.         filename:"bundle.js"    
  14.     },    
  15.     resolve: {   
  16.         extensions: [ '.js''.jsx']    
  17.     },  
  18.    module:{  
  19.        loaders:[  
  20.         {    
  21.             test:/\.js?$/,    
  22.             exclude: /node_modules/,    
  23.             include: /client/,    
  24.             loader:"babel-loader",    
  25.             query: {    
  26.            presets: ['es2015']    
  27.             }             
  28.         },  
  29.         {    
  30.             test:/\.jsx?$/,    
  31.             exclude: /node_modules/,    
  32.             include: /client/,    
  33.             loader:"babel-loader",    
  34.             query: {    
  35.            presets: ['es2015','stage-2','react']    
  36.             }     
  37.         }  
  38.        ]  
  39.    },  
  40.    devServer:{  
  41.        hot:true,  
  42.        port:4500  
  43.    }  
  44. }  
  45.   
  46. module.exports=config;  

In the above lines of code we write the configuration code for webpack , we define the entry and output path for the application . In output section we define that the name of the created bundle will be “bundle.js” and this bundle will be saved in “public” folder. The “publicPath” property defines how we can access this bundle into our application. The “extension” property of “resolve” defines which type of extension we are going to resolve. After that we add some loader that resolves the extension that we defined. In the last line of code we define the port number and hot development mode for running the application.

Now add a folder in root directory and name this folder as “public”, in this folder our “bundle.js” file will be saved. After creating the “public” folder now create another folder in root directory and name this folder as “client”. This folder provides the content for the client section of the application.

Now “client” folder has been created, let’s add a “app.js” file into this “client” folder. As we defined into webpack configuration this file will be the entry point for our application. Now paste the following code into this file.

App.js

  1. import React from 'react';    
  2. import ReactDOM from 'react-dom';    
  3. import Main from './components/main';  
  4. ReactDOM.render(<Main/>, document.getElementById('app'));   

In above code we import some required modules and write the code to render the content of “Main” component in “app” DOM element.

Add a “component” folder into “client” directory, in this “component” folder now create a “main.jsx” file in this fodler and paste the following code into this file.

Main.jsx

  1. import React from 'react';    
  2.     
  3. class Main extends React.Component {    
  4.    render() {    
  5.       return (    
  6.          <h2>    
  7.             Hello React!!!    
  8.          </h2>    
  9.       );    
  10.    }    
  11. }    
  12.     
  13. export default Main;    

So far we have created all the required files. Following will be the structure of our application.

React

After creating the setup for client app now open the command line terminal and run the “webpack-dev-server --hot” command, this command run the “webpack” dev server in hot(watch) mode and run the application on “4500” port.

React

Now paste the “http://localhost:4500/ “url in your browser, if you get the following screen that means our client side application is configured successfully.

React

Now go to the “main.jsx” file and make changes into content of “h2” element. When you make any changes and save these changes you will find that changes are automatically reflected into the browser. We don’t need to refresh the browser and see the changes because we run the webpack in hot mode, which means webpack watches for the changes and automatically refreshes the browser if and when changes are made.

Step 4 Add Typescript configuration

We can use the TypeScript with JSX, TypeScript provides the embedding, type checking and compiling JSX directly into JavaScript. To use the TypeScript into JSX first of all we need to add TypeScript configuration file into project. Now add the “tsconfig.json” file into root directory and paste the following code into this file.

tsconfig.json

  1. {  
  2.     "compilerOptions": {  
  3.       "jsx""react",  
  4.       "module""commonjs",  
  5.       "noImplicitAny"true,  
  6.       "preserveConstEnums"true,  
  7.       "removeComments"true,  
  8.       "target""ES6",  
  9.       "allowSyntheticDefaultImports"true  
  10.     },  
  11.     "exclude": [  
  12.       "node_modules",  
  13.       "typings/browser.d.ts",  
  14.       "typings/browser"  
  15.     ]  
  16.   }  

After adding this file now we need to add the some TypeScript packages. Run the below command to install the required TypeScript packages into the application.

  1. npm install --save-dev typescript ts-loader  
  2. npm install --save @types/react @types/react-dom  

First command add the TypeScript and “ts-loader” packages. The “ts-loader” package compiles the “tsx” code into simple JavaScript. The second command adds some dependent packages that provide the guidance to TypeScript compiler how to compile code for React application.

After installing the “TypeScript” related packages not we need to make the changes into our “webpack.config.js” file , so replace the code of this file with the following code.

  1. var webpack=require('webpack');  
  2. var path=require("path");    
  3. var srcPath=path.resolve(__dirname,"client");    
  4. var distPath=path.resolve(__dirname,"public");   
  5. var config={  
  6.     devtool:'source-map',  
  7.     entry:[  
  8.         srcPath+"/app.js"  
  9.     ],  
  10.     output:{    
  11.         path:distPath,    
  12.         publicPath: '/',  
  13.         filename:"bundle.js"    
  14.     },    
  15.     resolve: {   
  16.         extensions: [ '.js''.jsx','.ts','.tsx']      
  17.     },  
  18.    module:{  
  19.        loaders:[  
  20.         {    
  21.             test:/\.js?$/,    
  22.             exclude: /node_modules/,    
  23.             include: /client/,    
  24.             loader:"babel-loader",    
  25.             query: {    
  26.            presets: ['es2015']    
  27.             }             
  28.         },  
  29.         {    
  30.             test:/\.jsx?$/,    
  31.             exclude: /node_modules/,    
  32.             include: /client/,    
  33.             loader:"babel-loader",    
  34.             query: {    
  35.            presets: ['es2015','stage-2','react']    
  36.             }     
  37.         },  
  38.         {  
  39.             test: /\.tsx?$/,  
  40.             loader: "ts-loader",  
  41.             exclude: /node_modules/  
  42.         }  
  43.        ]  
  44.    },  
  45.    devServer:{  
  46.        hot:true,  
  47.        port:4500  
  48.    }  
  49. }  
  50.   
  51. module.exports=config;  

So far we made all the required configurations to implement in TypeScript functionality with JSX. So change the name of “main.jsx” file to “main.tsx” file and paste the following code into this file.

  1. import * as React from 'react';  
  2. export default class Main extends React.Component<any, any>   
  3. {  
  4.     render() {  
  5.         return (  
  6.             <div>  
  7.         <h2>Hello React with TypeScript</h2>  
  8.             </div>  
  9.     );  
  10.     }  
  11. }    

In the above line of code we write the same code as previous “jsx” file only difference is that now we are writing the code into “TypeScript” format.

Save all the changes and run the “webpack-dev-server --hot” command and refresh the browser. If everything is configured correctly then following output will be generated.

React

Step 4 Configure the Client App with backend

So far we have configured the client(front end) and sever side of the application but it is not a good approach to run react app and node.js server at two different ports. So we need a middleware in our “server.js” file that can provide the webpack features into express style format.

To implement the “webpack-dev-middleware” we need to add a required package, so run the below command to install this package.

npm install --save-dev webpack-dev-middleware

After installing the above package now we need to make some changes into “server.js” file, so replace the code of “Server.js” file with following code.

Server.js

  1. var express=require('express');  
  2. var path=require('path');  
  3. var app=express();  
  4. var webpack= require('webpack');  
  5. var config= require('./webpack.config');  
  6. const compiler = webpack(config);  
  7.   
  8. var port=5000;  
  9. app.get('/',function(req,res){  
  10.     res.sendFile(path.join(__dirname, './index.html'));  
  11. });  
  12. app.get('/api',function(req,res){  
  13.     res.send('<p>This is a api Data</p>');  
  14. });  
  15. app.use(require('webpack-dev-middleware')(compiler, {  
  16.     noInfo: true,  
  17.     publicPath: config.output.publicPath  
  18. }));  
  19. app.listen(port,function(error){  
  20.     if(error) {  
  21.         console.log(error);  
  22.     } else {  
  23.         console.log("Application running on port: "+port);  
  24.     }  
  25. })  

In the above line of code we import the webpack package and add the “webpack-dev-middleware” middleware into express server with some default configuration. After making the above configuration now run the “npm run node” command.

React

You will find that this command runs the nodemon server and also creates the “bundle.js” file. Now if you make any changes into either server.js file our react file will create a new bundle and changes are reflected when you refresh the browser. Congrats your React application has been setup, now you can do your thing.

Conclusion

In this article we took a small journey on how to set up a React app using the Node.js, Webpack and Typescript. Using the express you can define all your APIs and server level tasks and at React part (client side) you can access these APIs to get the data from server. You can download the source code for this project from the given below link.

 

If you have any queries or find any issues during the setup then write in the comment section. Thanks for reading this article.