How to Build a React App using Webpack, Node.js and Typescript

In this article we will learn how to set up a React project using Webpack, Node.js and Typescript. Start to set up our project, setup 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.

Step 2: Setup Node Server

Now run the below command into terminal window.

npm install --save express

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.

var express=require('express');  
var path=require('path');  
var app=express();  
var port=5000;  
app.get('/',function(req,res){  
    res.send('<html><body><h2>Congrts!!! Server Configured</h2</body></html>');  
});  
app.get('/api',function(req,res){  
    res.send('<p>This is a api Data</p>');  
});  
app.listen(port,function(error){  
    if(error) {  
        console.log(error);  
    } else {  
        console.log("Application running on port: "+port);  
    }  
})  

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.

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.

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”

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.

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

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.

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.

<html>  
    <head>  
        <title>  
            MEAN Stack  
        </title>  
    </head>  
    <body>  
        <div id="app"></div>  
        <script src='bundle.js'></script>   
    </body>  
</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.

var webpack=require('webpack');  
var path=require("path");    
var srcPath=path.resolve(__dirname,"client");    
var distPath=path.resolve(__dirname,"public");   
var config={  
    devtool:'source-map',  
    entry:[  
        srcPath+"/app.js"  
    ],  
    output:{    
        path:distPath,    
        publicPath: '/',  
        filename:"bundle.js"    
    },    
    resolve: {   
        extensions: [ '.js', '.jsx']    
    },  
   module:{  
       loaders:[  
        {    
            test:/\.js?$/,    
            exclude: /node_modules/,    
            include: /client/,    
            loader:"babel-loader",    
            query: {    
           presets: ['es2015']    
            }             
        },  
        {    
            test:/\.jsx?$/,    
            exclude: /node_modules/,    
            include: /client/,    
            loader:"babel-loader",    
            query: {    
           presets: ['es2015','stage-2','react']    
            }     
        }  
       ]  
   },  
   devServer:{  
       hot:true,  
       port:4500  
   }  
}  
  
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

import React from 'react';    
import ReactDOM from 'react-dom';    
import Main from './components/main';  
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

import React from 'react';    
    
class Main extends React.Component {    
   render() {    
      return (    
         <h2>    
            Hello React!!!    
         </h2>    
      );    
   }    
}    
    
export default Main;    

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

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.

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.

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

{  
    "compilerOptions": {  
      "jsx": "react",  
      "module": "commonjs",  
      "noImplicitAny": true,  
      "preserveConstEnums": true,  
      "removeComments": true,  
      "target": "ES6",  
      "allowSyntheticDefaultImports": true  
    },  
    "exclude": [  
      "node_modules",  
      "typings/browser.d.ts",  
      "typings/browser"  
    ]  
  }  

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.

npm install --save-dev typescript ts-loader  
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.

var webpack=require('webpack');  
var path=require("path");    
var srcPath=path.resolve(__dirname,"client");    
var distPath=path.resolve(__dirname,"public");   
var config={  
    devtool:'source-map',  
    entry:[  
        srcPath+"/app.js"  
    ],  
    output:{    
        path:distPath,    
        publicPath: '/',  
        filename:"bundle.js"    
    },    
    resolve: {   
        extensions: [ '.js', '.jsx','.ts','.tsx']      
    },  
   module:{  
       loaders:[  
        {    
            test:/\.js?$/,    
            exclude: /node_modules/,    
            include: /client/,    
            loader:"babel-loader",    
            query: {    
           presets: ['es2015']    
            }             
        },  
        {    
            test:/\.jsx?$/,    
            exclude: /node_modules/,    
            include: /client/,    
            loader:"babel-loader",    
            query: {    
           presets: ['es2015','stage-2','react']    
            }     
        },  
        {  
            test: /\.tsx?$/,  
            loader: "ts-loader",  
            exclude: /node_modules/  
        }  
       ]  
   },  
   devServer:{  
       hot:true,  
       port:4500  
   }  
}  
  
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.

import * as React from 'react';  
export default class Main extends React.Component<any, any>   
{  
    render() {  
        return (  
            <div>  
        <h2>Hello React with TypeScript</h2>  
            </div>  
    );  
    }  
}    

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.

Step 5: 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

var express=require('express');  
var path=require('path');  
var app=express();  
var webpack= require('webpack');  
var config= require('./webpack.config');  
const compiler = webpack(config);  
  
var port=5000;  
app.get('/',function(req,res){  
    res.sendFile(path.join(__dirname, './index.html'));  
});  
app.get('/api',function(req,res){  
    res.send('<p>This is a api Data</p>');  
});  
app.use(require('webpack-dev-middleware')(compiler, {  
    noInfo: true,  
    publicPath: config.output.publicPath  
}));  
app.listen(port,function(error){  
    if(error) {  
        console.log(error);  
    } else {  
        console.log("Application running on port: "+port);  
    }  
})  

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.

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.

Thanks for reading this article.

#react #webpack #node-js #typescript

How to Build a React App using Webpack, Node.js and Typescript
45.75 GEEK