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

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

This post, we'll learn about deploy and setup a React project using Webpack, Node.js and Typescript. Create package.json file. Setup Node Server. Setup Client App. Add Typescript configuration. Configure the Client App with backend

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.

Hire React Js Developer from Expert React JS Development Company

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

Are you looking to hire React JS developer from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team of expert React JS developers, you can hire them on an hourly, weekly or monthly basis for the successful completion of your dream project.

Getting Started with React, TypeScript and Webpack

Getting Started with React, TypeScript and Webpack

Here's my take on a starter project using React, TypeScript and Webpack.

Here's my take on a starter project using React, TypeScript and Webpack.

Getting Started

This will be a tutorial on getting a very bare-boned project up and running using React, TypeScript and Webpack. Alternatively you can skip directly to the source, available on my GitHub (complete with instructions) on getting the project up and running.

Setting up the project

  • Create a folder for your project.
mkdir your-folder-name && cd your-folder-name && npm init --yes

  • Install React and React-DOM as dependencies of the project.
npm install react && npm install react-dom

  • Under our devDependencies we need TypeScript.
npm install typescript --save-dev

  • Along with the Typings for React and React-DOM.
npm install @types/react --save-dev && npm install @types/react-dom --save-dev

  • Next we can initialize our TypeScript project. You should see a tsconfig.json file being created.
tsc --init

  • Open tsconfig.json, adding an include array after compilerOptions. This will tell TypeScript where to look for our code.
{
    "compilerOptions": {
    },
    "include":[ 
        "./src/**/*"
    ]
}

  • Now create a src folder, and inside create an App.ts file.
export class App
{
    constructor()
    {
        console.log("Hello app!");
    }
}

  • Test TypeScript is compiling by running tsc in the terminal. If successful, you should see an App.js file output to the src folder. Once it does, go ahead and delete the .js file once it appears.
Getting TypeScript and React working together

Now we have TypeScript compiling we can look at getting it to work with React files too.

  • In our tsconfig.json file, update yours to match the below.
{
    "compilerOptions": {
        "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
        "jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
        "sourceMap": true, /* Generates corresponding '.map' file. */
        "outDir": "./dist/", /* Redirect output structure to the directory. */
        "removeComments": true, /* Do not emit comments to output. */
        "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
        "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
        "preserveConstEnums": true
    },
    "include": [
        "./src/**/*"
    ]
}

  • To test TypeScript will now pick up React files, we'll add a new file to our src folder called Main.tsx.
    import * as React from 'react';
    import { App } from './App';

    export interface IMainProps
    {
        app: App;
    }

    export class Main extends React.Component<IMainProps, {}>
    {
        public render(): JSX.Element
        {
            return (
                <>
                    <h1>Hello main</h1>
                </>
            );
        }
    }

  • Run tsc in your terminal, and you should now see a dist folder appear with a Main.js file, which means TypeScript is now also picking up React TypeScript files! (.tsx)
Adding Webpack to the mix

We now have TypeScript and React working together. What we need next, is for Webpack to bundle it all up and serve it in our browser.

First, we're going to install Webpack locally, as recommended by the official Webpack documentation.

  • Run the following in your terminal
    npm install webpack --save-dev && 
    npm install webpack-cli --save-dev && 
    npm install webpack-dev-server --save-dev && 
    npm install awesome-typescript-loader --save-dev && 
    npm install html-webpack-plugin --save-dev

  • We've now installed Webpack with four additional devDependencies

  • Let's go ahead and create our webpack.config.js file in the root of our project.

    const path = require('path');
    const HtmlWebPackPlugin = require('html-webpack-plugin');

    module.exports = {
        entry: {
            app: ['./src/App.ts'],
            vendor: ['react', 'react-dom']
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'js/[name].bundle.js'
        },
        devtool: "source-map",
        resolve: {
            extensions: [".ts", ".tsx", ".js", ".jsx", ".json"]
        },
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    loader: "awesome-typescript-loader"
                }
            ]
        },

        plugins: [
            new HtmlWebPackPlugin({
                template: "./src/index.html"
            })
        ]
    };

Things to note:
  • Our entry object contains a path to App.ts file we made earlier.
  • It also includes a vendor array, React and React-Dom are our only libraries, so we add these here. If you want to add additional libraries, you should add them to this so Webpack knows about it.
  • Our output object tells webpack where to bundle our app, which in this case is our dist folder.
  • Under module we've added our awesome-type-script-loader.
  • Under our plugin array, we've added our source index.html file using the HtmlWebPackPlugin. A minified html file will get placed in our dist folder along with the reference to our bundled up js files.

Next, create a new index.html file and add it to our src folder. Make sure there is <div id="app"></div> in yours. This is where our React app will look to render to.

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>App</title>
    </head>

    <body>
        <div id="app"></div>
    </body>

    </html>

  • Open App.ts and add to the very bottom of the file new App();
export class App
{
    constructor()
    {
        console.log("Hello app!");
    }
}

new App();

  • Now in the root folder of the project, run in the terminal
node_modules/.bin/webpack-dev-server  --mode development

  • You should now have a successful build, with a webserver at http://localhost:8080/.
  • Inspecting the dev console (F12 > console), you should also see our log in the console outputting "Hello app!"
Making it more React

Now that we have React, TypeScript and Webpack all playing nicely, let's actually get some React rendering.

  • Create a Main.tsx file and paste in the below.
    import * as React from 'react';
    import { App } from './App';

    export interface IMainProps
    {
        app: App; // Reference to our App.ts class
    }

    export class Main extends React.Component<IMainProps, {}>
    {
        constructor(props: IMainProps)
        {
            super(props);
        }

        public render(): JSX.Element
        {
            return (
                <>
                    Main app
                </>
            );
        }
    }

  • Open App.ts file and paste in the below.
    import * as ReactDOM from 'react-dom';
    import * as React from 'react';
    import { Main } from './Main';

    export class App
    {
        constructor()
        {
            this.render();
        }

        private render(): void
        {
            ReactDOM.render(React.createElement(Main, { app: this }), document.getElementById("app"));
        }
    }

    new App();

Things to note here:
  • We're rendering our Main.tsx class as our main React UI.
  • We're passing in a reference to our App class as a react prop. There might be stuff we want to do or access in our App class at a later date.
  • We're passing in our app id element we added to our index.html file earlier. This will be where React will render.

Now if we go back to our browser, we should see "Main app" on our page. Your browser should have auto-reloaded since we changed some code.
React has now landed on our webpage.

Tidying up and publishing

Typing in ./node_modules/.bin/webpack-dev-server --mode development just to run the dev server everytime isn't great.
We can change this into a more friendly node command.

Open up our package.json file and update the scripts object so it looks like below:

{
    "scripts": {
        "dev": "webpack-dev-server --mode development",
        "build": "webpack --mode production"
    }
}

We can now run our above commands in the terminal:

  • Running npm run dev is now doing what we were typing earlier: ./node_modules/.bin/webpack-dev-server --mode development

  • Running npm run build will tell webpack to compile our app for production. It will essentially minify everything and bundle it into our
    dist folder, ready to upload to the web.

Source code

And that's it! You now have TypeScript, React and Webpack playing nice.

As mentioned at the start, you can find the source code on my GitHub.
It also includes a very basic look at React components and adding them to our Main.tsx file.

Feel free to give it a star if it's helped you out.