AppDividend
Latest Code Tutorials

Beginner’s Guide to Setup TypeScript with Webpack

2

TypeScript is a free and open-source programming language developed by Microsoft Team. It is a  superset of JavaScript and statically typed object-oriented programming language. It is a very modern static typing language used by Angular Framework. Today, we will learn how to configure typescript in our machine to use its features.

If you go to its official website http://www.typescriptlang.org/docs/tutorial.html, you will find step by step to install the typescript on your machine.

But I am also writing this post to understand that configure TypeScript or ECMA Script will do pretty much the same thing. So I will go through you every step and also how to integrate with a webpack.

Let’s start Setup TypeScript with the Webpack tutorial.

If you are taking this demo then on your local machine, you would have to have node.js install.

Step 1: Install Typescript globally on your machine.

npm install -g typescript

Step 2: Create a project folder.

Next, you will create a project folder and navigate to it.

mkdir typescript
cd mkdir

Step 3: Create a file called app.ts

Save the filename with the .ts extension.

Now, write the following code in app.ts.

function greeter(person: string) {
    return "Hello, " +person;
}

var krunal = greeter('krunal');
console.log(krunal);

Here in the function’s argument, we have specified that the parameter will be definitely “string,” which is one type of TypeScript feature.

Now we need to compile this file, and the output of this file is a Javascript file.

So go to the terminal and type the following command.

tsc app.ts

We have installed TypeScript globally. So app.ts file is compiled by TypeScript compiler and convert this file into vanilla javascript.

This file will reside in the same folder as our typescript file.

Now create one file in the root folder called index.html

Include the newly compiled app.js and run it in the browser.

You will get in a chrome developer tool’s console panel “Hello Krunal.”

Great!! So we have written one typescript file. Next, convert it into a Javascript file and finally include the script on our web page.

Step 4: Configure tsconfig.json

We are using TypeScript, so we need to create and set up a file called tsconfig.json.

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "src/*"
  ],
  "compileOnSave": true
}

The tsconfig.json is our TypeScript configuration file, which contains an object.

compilerOptions: This object includes module – which is the common.js pattern, we want to target to ES5 way, and we have the source maps so that when we debug, we can see an error in typescript file.

exclude: We need to exclude compilations from node_modules folder

include: Which files in our project will be compiled from TypeScript to Javascript, this property will tell us.

compileOnSave: When we save our TypeScript file, It will immediately transpile the TypeScript file to a Javascript file.

We don’t need to compile every time via command, and we need to write a typescript file and save it. Then, the compiler will automatically compile that file and create one javascript file.

Step 5: Edit the app.ts file.

Again, we change the code of app.ts.

function greeter(person: string) {
    return "Hola, " +person;
}

var krunal = greeter('Senorita');
console.log(krunal);

When we open the index.html file, you will be able to see “Hola, Senorita.”

You can learn more about the tsconfig.json file at this official link: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html.

Step 6: Create package.json file and install webpack and webpack-dev-server.

We want to use a webpack to transpile TypeScript into Javascript code.

To manage node dependencies, we had to have the package.json file.

npm init

Next, we need to install a webpack and webpack-dev-server in our project.

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

Now we need to install a local TypeScript compiler and the TypeScript loader.

npm install --save-dev typescript ts-loader

So your package.json file will look like this.

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "ts-loader": "^2.0.3",
    "typescript": "^2.2.2",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Next, your tsconfig.json file will look like this.

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "outDir": "./src/",
    "noImplicitAny": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "src/*"
  ]
}

Since we will use a webpack to transpile the file, we don’t need compileOnSave property on the JSON object.

Step 7: We need to create a webpack.config.js file to export the configuration object.

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

The webpack.config.js file exports a javascript object contains typescript settings.

The object includes the entry: which is the main typescript file we need to compile, then output: what is the output file name and which is its path, next module object which contains rules and resolves array.

States include the test which extension file we need to compile, loader tells which loader we will use to work done. In our case, we have already download the ts-loader. Exclude contains, which folder we don’t need to include in our transpile process.

Now, update our package.json file.

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "ts-loader": "^2.0.3",
    "typescript": "^2.2.2",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  },
  "scripts": {
    "start": "webpack-dev-server",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Our final project directory structure will look like this.

Beginner's Guide To Setup TypeScript With Webpack
Beginner’s Guide To Setup TypeScript With Webpack

Change the index.html file’s script tag to the following.

<script src="bundle.js" type="text/javascript"></script>

Again,  go to the terminal and type.

npm start

If the webpack compiles successfully, then we will be able to see it in the http://localhost:8080.

In the console panel, we will still get the same thing.

So we have a bundled typescript file, which we have to include in our project.

You can see this code from my Github repo.: https://github.com/KrunalLathiya/typescript-webpack-env.

Note:  If you find any error during this small setup,

  1. First, check your node and npm versions
  2. Check off your dependencies version by comparing the package.json file with yours because you might end up downloading another version of that particular dependencies.

That is it for the Setup TypeScript with Webpack.

If you have any questions, please ask in a comment below. I am happy to help you out.

2 Comments
  1. Hardik says

    Very easy to understand

  2. Sriharsha says

    thank you!!!
    Appreciated for the quick steps

Leave A Reply

Your email address will not be published.

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