Beginner’s Guide To Setup TypeScript With Webpack

Hello, Web Artisans.  In today’s AppDividend Tutorial, I have briefly described Beginner’s Guide To Setup TypeScript With Webpack in our local machine.

TypeScript, It 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 very modern static typing language used by Angular 2 Framework. Today, we will learn how to configure typescript in our machine so that we can 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 so that you will understand that configure TypeScript or ECMA Script will do pretty much the same thing. I will go through you each and every step and also how to integrate with webpack.

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 output of this file is javascript file.

So go to the terminal and type

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 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 in the browser.

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

Great!! So we have written one typescript file. Convert it into 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
}

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 then, It will immediately transpile TypeScript file to Javascript file.

Now, we don’t need to compile every time via command, and we just need to write typescript file and save it. The compiler will automatically compile that file and create one javascript file.

Step 5: Edit 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 able to see “Hola, Senorita.”

You can learn more about tsconfig.json file in 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 webpack for transpile TypeScript into Javascript code.

For manage node dependencies, we had to have the package.json file right?

npm init

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

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

Now we need to install locally 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 webpack to transpile the file, we don’t need compileOnSave property on the JSON object.

Step 7: We need to create webpack.config.js file to export 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"]
    },
};

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

Object include entry: which is the main typescript file we need to compile it down, 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 go to use to work done. In our case, we have already download ts-loader. exclude contains, which folder we don’t need to include in out 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

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

Again,  go to terminal and type

npm start

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

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

So we have 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 package.json file with yours because you might end up with downloading another version of that particular dependencies.

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

Leave A Reply

Your email address will not be published.