• Technicalpig
  • Posts
  • TechnicalPig🐷: 7 simple steps to build a Node.js Typescript project

TechnicalPig🐷: 7 simple steps to build a Node.js Typescript project

Easy to follow guide

TechnicalPig🐷: 7 simple steps to build your own Node.js and Typescript project

1. Create your directory

In your chosen folder, run:

mkdir your-project-name

this will create the project which will store our code.

2. Change working directory to

Run the command line instruction used to change the current working directory to a directory named "project".

cd your-project-name

3. Initialise project

Once you are in the right directory, initialise your project.

Initialising refers to the process of setting up a new project in Node.js using npm. This process creates a new package.json file in your project directory which is a fundamental component for managing project dependencies, scripts and metadata.

To initialise, run:

npm init -y
  • this command will prompt you to enter several pieces of information (e.g. project’s name). You can skip this step by including -y like we did above. This will create a package.json with default values.

  • you can always edit these details later by directly modifying the package.json file.

4. Install Typescript

To install Typescript, run:

npm install —save-dev typescript

You can read more about Typescript here: https://www.typescriptlang.org/download 

5. Create your tsconfig file

tsconfig is a vital configuration file for typescript projects. It specifies the root files and the compiler options required to compile the project using Typescript.

You can copy the following code into your own tsconfig.json file that should be in your project directory

{ "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "target": "es6", "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "resolveJsonModule": true, }, "lib": ["es2015"] }

6. Invoke Typescript compiler

To invoke the compiler, run:

npx tsc
  • This command invokes the Typescript compiler through npx (Node Package Execute).

  • This command compiles Typescript files (.ts) into Javascript (.js) files based on the configurations specified in tsconfig.json.

  • The output of these typescript files is determined by the settings in your tsconfig.json file. In the example above, they can be found in your dis folder (see outDir).

7. Run your project

Create an index.ts file inside your project. To check that the set up is working, you can try something simple like logging a string to your console - write this code in your index.ts file:

console.log('hello world')

To run your project, run the Typescript compiler first:

npx tsc

Next, run:

node dist/index.js

You should see hello world printed in your console!

Summary

These are 7 simple steps to get you started on building your own Typescript and Node.js project!