Get start with Typescript and Parcel

Get start with Typescript and Parcel

Setup your dev environment with Parcel and Typescript.

Typescript is a technology that grows every day. Companies like Slack, Airbnb, or Google are changing their javascript codebase to Typescript.

Frameworks like Vue, React, and (Angular) are using Typescript for writing maintainable code.

These steps show how to start a project with Typescript and Parcel.

The complete code is available https://github.com/danywalls/hello-typescript.

Create a basic project structure

The app structure is a simple two typescript class (User.ts, App.ts) and index.html.

app/App.ts
app/User.ts
index.html

Setup Parcel and NPM Tasks

The parcel is an npm package for transforming, compile and bundling assets. It also provides a development server with a hot-reload.

The first step is installing the packages dependencies.

npm install -D parcel parcel-bundler

Create dev and build script in package.json. These tasks help define tasks to run the dev server.

"scripts": {
        "dev": "parcel index.html",
        "build": "parcel build dist"
    }

Ready to code?

The User.ts file is a class. The class has a constructor with two parameters, name and age.

The hello method returns a string with the name and age.

export class User {
    constructor(public name: string = "no name", public age: Number = 35) { }
    hello(): string {
        return `Hi ${this.name} your age is ${this.age} `;
    }
}

Import the User class into the App.ts. Add a function for window.onload event. The process sets the title with the return of the hello method.

import { User } from "./User";

window.onload = () => {
  let title = document.querySelector("#title");
  const tsUser = new User("Dany Paredes", 36);
  if (title) title.innerHTML = tsUser.hello();
};

Edit index.html file and import App.ts

<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello Typescript</title>
</head>
<body>
    <div name="container">
        <h2 id="title"></h2>
    </div>
    <script src="app/App.ts"></script>
</body>
</html>

Run the npm run dev command to start the webserver at localhost:1234.

Final

That gives a head-start on Typescript, and if you enjoyed it, please share.

Photo by Braden Collum on Unsplash