How to Set Up a Node.js Project with TypeScript
Step 1 — Initializing the Project
Now, we need to create the project folder:
Then cd
into that project folder:
Now we’re ready to initialize a node package:
Once you’ve reached the last step it will say:
Hit enter and you’ll see your new package.json
file that should look something like this:
Step 2 — Configuring the TypeScript Compiler
Now that your npm project is initialized, you are ready to install and set up TypeScript.
Run the following command from inside your project directory to install the TypeScript:
TypeScript uses a file called tsconfig.json
to configure the compiler options for a project. Create a tsconfig.json
file in the root of the project directory:
Then paste in the following JSON:
Let’s go over some of the keys in the JSON snippet above:
module
: Specifies the module code generation method. Node usescommonjs
.target
: Specifies the output language level.moduleResolution
: This helps the compiler figure out what an import refers to. The valuenode
mimics the Node module resolution mechanism.outDir
: This is the location to output.js
files after transpilation. In this tutorial you will save it asdist
.
Step 3 — Create TypeScript Express Server
Now, it is time to install the Express framework and create a server:
for types support:
The above command installs the Express types for TypeScript support. Types in TypeScript are files, normally with an extension of .d.ts
. The files are used to provide type information about an API, in this case the Express framework.
This package is required because TypeScript and Express are independent packages. Without the @types/express
package, there is no way for TypeScript to know about the types of Express classes.
Next, create a src
folder in the root of your project directory:
Then create a TypeScript file named app.ts
within it:
now we can write our typescript code in app.ts:
The code above creates Node Server that listens on the port 3000
for requests. To run the app, you first need to compile it to JavaScript using the following command:
Javascript compiled code
Run the JavaScript output with node
:
final code: