React webpack typescript setup step by step

react typescript starter create react app typescript react typescript boilerplate typescript react component react with typescript example react redux typescript awesome-typescript-loader awesome-typescript-loader vs ts-loader

React WebPack and TypeScript environment setup is the first step to learn react, it is easy but seems too much settings. In this article we will see how can we do it without knowing anything about React, Webpack and typescript, rest of the things we can learn latter, once we will have environment setup. We will do it by using Visual Studio Code.

Create a folder where you want to keep the project say "react-evn".

Open Visual Studio Code, from file menu open your created folder.

Open "Integrated Terminal" from View menu.

To start we need Nodejs to be installed, so check if you already have installed node or not?

node -v

If it is not installed, install it from https://nodejs.org/en/download/ according to you system.

React Webpack and Typescript configuration step by step

Once nodejs is installed, check npm is working or not by checking npm version, use

npm -v

Now we need to initialize the application by using npm init command

npm init -y

It will create package.json file, -y will force to use the default values for setting, open the file and see if you can change anything like description, auther, license etc. but it is not required.

If you will create the folder name having any capital letter then it will show error for name, so change that to lower case.

First of all we will install some packages, run following commands one by one:

// Install React
npm i --save react react-dom
npm i --save-dev @types/react @types/react-dom
// Install Webpack
npm i --save-dev webpack webpack-dev-server webpack-cli 
npm i --save-dev html-webpack-plugin
// Install TypeScript
npm i --save-dev typescript awesome-typescript-loader

We are using typescript, so we need to configure it, create a new json file on root and name it tsconfig.json, add following setting in it. You don't need to change anything so just do the copy paste.

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "jsx": "react",
        "module": "commonjs",
        "noImplicitAny": true,
        "outDir": "./dist",
        "preserveConstEnums": true,
        "removeComments": true,
        "sourceMap": true,
        "target": "es5"
    },
    "include": [
        "./src/**/*"
    ]
}

We are including files from the folder src, so create a new folder named src on the root, in which we will keep our files.

Create a new file on the root for webpack setting, name it webpack.config.js and add following code in it:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
    entry: "",
    mode: "",
    output: {},
    module: {},
    plugins:[]
}

This is the complete setting of webpack, once we will complete this part, we will have a working environment.

entry: An entry point indicates which module webpack should use to begin building out its internal dependency graph.

Create a new file in src folder and name it index.tsx, this would be our first page, latter we will add code in it, let's first complete our settings. So set it to

entry: "./src/index.tsx",   

Mode: mode of application environment development/production

Let's use the environment to development

mode: "development",

output: The output property tells webpack where to emit the bundles it creates and how to name these files, it defaults to ./dist/main.js for the main output file and to the ./dist folder for any other generated file.

output:{
    path: path.resolve(__dirname, "dist"),
    filename: 'main_scripts.js'    
},

Where __dirname is always the directory in which the currently executing script resides. We can give any name to our output js file name.

module: Webpack only understands JavaScript files. Loaders allow webpack to process other types of files and converting them into valid modules that can be consumed by our application and added to the dependency graph.

We are using the typescript, so they need to be converted to JavaScript:

module: {
    rules:[
        {
            test:/\.tsx/,
            loader: "awesome-typescript-loader"
        }
    ]
},

We are using here awesome-typescript-loader to convert the TypeScript to JavaScript.

plugins: While loader are used to convert the files, plugins have many tasks like, building, minifiying, optimization, assets management and injection of environment variables.

Whatever the files will be generated from Loaders in module need to be referenced in index.html file. Let's complete the configuration then we will create the index.html file on the root.

const HtmlWebpackPlugin = require('html-webpack-plugin');
.....   
plugins: [new HtmlWebpackPlugin({
        template: './index.html'
    })
]

Note we gave the template file name as index.html on the root, so let's create it:

<!DOCTYPE html>
<html>
  <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>React Typescript App</title>
  </head>

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

There is nothing new, it's very basic html page. No need to set the script src, webpack will automatically add in it.

Note the div inside the body with id app, we will use this Id to load our components in it.

While we were discussing entry point we created a file index.tsx inside the src folder and left that blank. Lets add some basic react code in it:

import * as React from 'react';
import * as ReactDOM from 'react-dom';

class Index extends React.Component<any, any> {
    render() {
        return (
            <div>   
                <h1>Index Page</h1>
                <p>We completed our setting and ready to explor more!</p>
            </div>
        );
    }
}
ReactDOM.render(<Index />, document.getElementById("app"));

It's nothing but a very basic react component with some static HTML.

We are done, let's see the complete webpack.config.js file:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: "./src/index.tsx",
    mode: "development",
    output:{
        path: path.resolve(__dirname, "dist"),
        filename: 'main_scripts.js'    
    },
    module: {
        rules:[
            {
                test:/\.tsx/,
                loader: "awesome-typescript-loader"
            }
        ]
    },
    plugins: [new HtmlWebpackPlugin({
            template: './index.html'
        })
    ]
} 

Wasn't it easy? Before running our application we need to create the command to start the application. Open package.json file which we crated very first by using npm init -y.

// Change this to
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
}
// This one
"scripts": {
    "start": "webpack-dev-server --open"
}

Now run the command

npm start

It will outomatically open your default browser and show the page, greate. If you don't want to open the browser again and again remove --open from start command and just build the application and refresh the page.

Next we will learn how to add SASS and Bootstrap 4 SASS.

Alicia Gonzalez Started career with .Net, and not working on client side technologies like angular, React etc. since last 12 years. But C# is really amazing language and I like to learn everything about C# and want to share whatever I know.
  • reactjs
  • webpack
  • typescript
By Alicia Gonzalez On 24 Jul, 18  Viewed: 196