Skip to content

Instantly share code, notes, and snippets.

@nivethan-me
Last active May 30, 2024 18:14
Show Gist options
  • Save nivethan-me/4e83e8a1666183eae9f54cc1f32a4c82 to your computer and use it in GitHub Desktop.
Save nivethan-me/4e83e8a1666183eae9f54cc1f32a4c82 to your computer and use it in GitHub Desktop.
Setup Node.js with TypeScript

Setup a Node.js v20 project with TypeScript v5 & pnpm as package manager


  1. create a new folder with the project name. and cd into it
mkdir node-with-ts
cd node-with-ts/
  1. create package.json with a package manager.(i'm using pnpm)
pnpm init
  1. Add type in the package.json
{
  "name": "node-with-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  1. Add typescript and node types to the project
pnpm add -D typescript @types/node
  1. Add a script to build the project in package.json
{
  "name": "node-with-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "build": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^20.12.13",
    "typescript": "^5.4.5"
  }
}
  1. Add tsconfig.json file to tell how to build our project to typescript compiler
touch tsconfig.json
{
  "compilerOptions": {
    "module": "nodenext",
    "target": "ES2020",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"]
}
  1. Create a typescript file inside src directory
mkdir -p src && touch src/index.ts
  1. Add some code into src/index.ts file to test the setup
type User = {
  name: string;
  age: number;
};

function isAdult(user: User): boolean {
  return user.age >= 18;
}

const justine: User = {
  name: 'Justine',
  age: 'Secret!',
};

const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!");
  1. After fixing the TypeScript errors run pnpm build which will create a dist folder with js files inside
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment