DEV Community

Linas Spukas
Linas Spukas

Posted on

Quick and Easy TypeScript Project Setup

One of the fastest and easiest ways to set up and run a TypeScript project in the browser is with the help of the web bundler Parcel. This command-line tool is fantastic, it offers built-in TypeScript support, development server, hot module replacement to track changes and reload, and it requires zero configuration. So it is a perfect tool to start a TypeScript project.

First, let's start by creating a project folder, setting up an npm package and install parcel-bundler locally:

mkdir myapp
cd myapp
npm init -y
npm install --save-dev parcel-bundler

The starting project structure will look like this:

myapp
│   index.html
│   package.js
│
└───src
    │   index.ts

We will feed an index.html as an entry file and make a reference to src/index.ts in the script tag:

<html>
<body>
    <script src="./src/index.ts"></script>
</body>
</html>

As soon as Parcel sees the TypeScript file in the script tag, it will parse it, compile to JavaScript file, replace script tag with a new compiled index.js file and run in the browser.

To run the app we need to call a parcel command with a path to an entry file, which is index.html. As we installed Parcel locally, we cannot just call parcel index.html within the project directory in a terminal. For that, we will use an npm script. In the package.js add following script commands for starting the development server (start) and building for production (build):

{
  "name": "myapp",
  ...
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html"
  },
  ...
  "devDependencies": {
    "parcel-bundler": "^1.12.4",
    "typescript": "^3.9.5"
  }
}

Both commands can be initiated from a terminal within the project directory with npm run start or npm run build. When you start a project with the start command, a local server will be built for you with the hot module reloading feature. Whenever you save changes, Parcel will recompile your code and reload the browser with the newest changes.

To test it up, add a simple console.log command to index.ts file and run the app. In the browser console, you should see your printed message.

Parcel is a magical tool. So easy and quick way to start your next project in minutes, and not only for TypeScript. Have fun and happy coding.

Top comments (2)

Collapse
 
vaov1999 profile image
VLAD

thx

Collapse
 
sebnozzi profile image
Sebastian Nozzi

Thanks for this article and the instructions. Very much appreciated.