How to Add TypeScript to a Node.JS Server With ts-node
We'll get started with TypeScript in this lesson by installing a few necessary packages in our server and setting up the configuration of our TypeScript compiler.
Adding TypeScript to our Server#
📝 This lesson's quiz can be found - here.
🗒️ Solutions for this lesson's quiz can be found - here.
To configure our Node server into a TypeScript project, we'll need to install and use certain TypeScript packages. We'll install the latest versions of the
ts-node libraries as development dependencies.
ts-nodeis a utility library that helps us run TypeScript programs in Node.
server $: npm install -D typescript ts-node
The first thing we'll do to introduce TypeScript into our Node server project is create a TypeScript configuration file (
tsconfig.json file is a JSON file that should be created at the root of a TypeScript project and indicates the parent directory is a TypeScript project.
tsconfig.json is where we can customize our TypeScript configuration and guide our TypeScript compiler with options required to compile the project.
To customize and edit the options of the TypeScript compiler, we'll specify a
compilerOptions key in our
There are a large number of options we can dictate and control in our compiler of which all can be seen in the TypeScript handbook. We're not going to go through all the different possible options but instead dictate the ones we'll use for our app.
We'll declare the
es6 since Node supports a vast majority of ES6 features.
We'll declare the
commonjs as the module option.
To specify the location of files for where we want to declare TypeScript code, we'll use the
rootDir option and give a value of
src/ to say we want our compiler to compile the Typescript code in the
We can use the
To help compile our CommonJS modules in compliance with ES6 modules, we'll need to introduce the
esModuleInterop option and give it a value of