There are many ways to add typescript to your project. Some require a huge amount of configuration and some are as easy as adding several code lines. I think one of the easiest ways to do so is to use a bundling tool like parceljs. With it, you can add typescript in a matter of minutes with pretty much no config required.
## What the heck is parceljs?
Parceljs is a super-fast web application bundler that works straight out of the box. I'm sure everyone has heard about webpack and while it is more powerful, it is a lot harder to set it up correctly.
Ready? Let's add typescript to our project
!!! Before we do anything, make sure that you have nodejs
and npm
installed !!!
To check whether we have those technologies installed use command in your terminal:
node --version
// v12.18.4
npm --version
// 6.14.6
If you don't have them installed, please go to :
- https://nodejs.org/en/ to install nodejs
- https://docs.npmjs.com/downloading-and-installing-node-js-and-npm guide to install npm
In the terminal create a new folder and move to it
mkdir my-awesome-ts-project && cd my-awesome-ts-project
The next step is to add package.json
npm init -y
// we will get
{
"name": "my-awesome-ts-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
We are almost done, the next step would be to add parceljs and typescript with npm install --save-dev typescript parcel-bundler
And that's it! Now you can create your .html
and .ts
files. Add script tag and voulia, typescript is ready!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="app.ts"></script>
</body>
</html>
One more thing, you will need to add one more line in package.json
to start your local development with parceljs.
Add this line to scripts{}
section "start": "parcel index.html"
Your final package.json
will look like this:
{
"name": "my-awesome-ts-project"",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "parcel index.html"
},
"author": "",
"license": "ISC",
"devDependencies": {
"parcel-bundler": "^1.12.4",
"typescript": "^4.0.2"
}
}
And that's it, now just run the command npm run start
and it will start the local development server.
app.ts
file will be compiled into javascript automatically, so you can write typescript like there's no tomorrow.
Top comments (0)