AppDividend
Latest Code Tutorials

How To Setup TypeScript With Webpack 4

7,766

Get real time updates directly on you device, subscribe now.

In this web tutorial, we will see how to setup typescript with webpack 4. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It is very modern static typing language used by Angular Framework. TypeScript is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. 

Setup TypeScript with Webpack 4

First, we need to install the typescript.

Step 1: Install Typescript globally on your machine.

Switch to your terminal and hit the following command to install typescript globally on your machine.

sudo npm install -g typescript

 

Step 2: Create a project folder.

Create a new project folder and go into that project.

mkdir tswebpack4
cd tswebpack4

Okay, now in the root folder, make one typescript file called index.ts and inside that file, we will write some typescript code.

// index.ts

function getName(name: String) {
    return name;
}

console.log(getName('krunal'));

The browser cannot understand the TypeScript code. So we want to transpile that code into the Javascript code. Now go to your terminal and hit the following command.

tsc index.ts

It transpiles the code into the Javascript, and you can see that in the root there is one created called index.js.

// index.js

function getName(name) {
    return name;
}
console.log(getName('krunal'));

Step 3: Configure tsconfig.json.

In the root folder,  make one file called tsconfig.json file.

{
    "compilerOptions": {
      "module": "commonjs",
      "target": "es5",
      "sourceMap": true
    },
    "exclude": [
      "node_modules"
    ]
  }

Step 4: Install webpack and ts dependencies.

We need to install the webpack and other as development dependencies.

npm install webpack webpack-cli webpack-dev-server --save-dev

Now we need to install locally TypeScript compiler and the TypeScript loader.

npm install typescript ts-loader --save-dev

Also, generate a package.json file by typing the following command.

npm init -y

Step 5: Create webpack configuration file.

Inside root folder, create one file called webpack.config.js.

const path = require('path');

module.exports = {
    entry: path.join(__dirname, '/app.ts'),
    output: {
        filename: 'app.js',
        path: __dirname
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
            },
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"]
    },
};

In this file,  we have defined the entry point file as an app.ts. So let us create that file first.

// app.ts

export class Hero {
    id: number;
    name: string;

    constructor(name) {
        this.name = name;
    }

    myName()
    {
        return this.name;
    }
  }

  let hero = new Hero('krunal');
  console.log(hero.myName());

Now, this file prints merely my name in the console but this code is in typescript, and we want to run this file in the browser. So we have defined the webpack.config.js file. In that, I have described entry, output, and the module that contains typescript loader that helps us to run the code in the javascript.

Okay when we run webpack-dev-server, it output the file named app.js. So app.js is the file we need to include the index.html file. We have not created the index.html file so, let us do it first.

<!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>Document</title>
</head>
<body>
    <script src="app.js" type="text/javascript"></script>
</body>
</html>

Step 6: Run the webpack development server.

Go to the package.json file and add the following script.

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

Now, go to the terminal and start the server.

npm start

 

Typescript webpack 4 tutorial

 Switch to the browser and go to this URL: http://localhost:8080/

In the console panel, you can see the name is printed. So we have successfully compiled typescript file into the javascript file.

So that is it for the How to setup typescript with webpack 4 tutorial.

 

 

 

2 Comments
  1. Saurabh says

    Hello,

    Suppose I have two typescript Bundle A and B with above methods shown.Then how can I use A in B

  2. Igor says

    Hello . Thank you for your tutorial .
    Q : Why i can’t find app.js in my directory ?

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.