Simple Nodejs and TypeScript Project Example
December 14, 2020
Quick Start
mkdir my-project
cd my-project
npm init -y
npm install typescript --save-dev
npm install rimraf --save-dev
touch tsconfig.json
touch index.ts
// tsconfig.json
{
"compilerOptions": {
"outDir": "./out",
"rootDir": "./",
"sourceMap": true,
"moduleResolution": "node",
"target": "es5"
}
}
// package.json
...
"scripts": {
"start": "node out/index.js",
"prestart": "rimraf out && npm run build",
"build": "./node_modules/typescript/bin/tsc"
},
...
// index.ts
console.log('Main entry point');
npm run start
Initial Setup
First, create the project directory and intialize the Nodejs project.
mkdir my-project
npm init -y
Running npm init -y
will create a package.json
file in the my-project
directory with default values populated. You can omit the -y
and run npm init
on its own if you’d like to set specific values at creation time, but they can always be changed later.
Install and Configure TypeScript
In the project root (where package.json
is) we will run the npm command to install TypeScript. We want to save TypeScript to our package.json
devDependencies
object, so we’ll include --save-dev
in the install command. For now, TypeScript is only needed during development, our “build” files will be JavaScript. We’ll also install the rimraf
package, which is a small utility for cleanly removing files or directories.
npm install typescript --save-dev
npm install rimraf --save-dev
Next, we’ll create a tsconfig.json
file in the root directory. This file contains all of the configuration settings for TypeScript. Here we will create a simple version of this file by hand.
While still in the project root directory:
touch tsconfig.json
And add the following JSON:
{
"compilerOptions": {
"outDir": "./out",
"rootDir": "./",
"sourceMap": true,
"moduleResolution": "node",
"target": "es5"
}
}
An important thing to note here is the "outDir": "./out"
, which is where the transpiled JavaScript files will go after we run npm run start
You can have the TypeScript compiler create a more complete version of tsconfig.json
for you via tsc --init
(if you have TypeScript installed globally) or ./node_modules/typescript/bin/tsc --init
from project root.
Compiling and Running
Next we’ll update our package.json
file. Add (or update) the following script commands in the scripts
block:
"start": "node out/index.js",
"prestart": "rimraf out && npm run build",
"build": "./node_modules/typescript/bin/tsc"
The prestart
command will excute each time you run npm run start
. In our case, it removes the old out
directory and runs the build command.
Before we can run npm run start
we’ll need an index.ts
file since we specified index.js
as our main
entry point in the package.json
.
// index.ts
console.log('Main entry point');
Now we can run npm run start
. “Main entry point” should be printed to the console and the out
directory should be created in the project root containing an the index.js
file.