Setup a Node.js v20 project with TypeScript v5 & pnpm as package manager
create a new folder with the project name. and cd into it
mkdir node-with-ts
cd node-with-ts/
create package.json with a package manager.(i'm using pnpm)
pnpm init
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"
}
Add typescript and node types to the project
pnpm add -D typescript @types/node
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"
}
}
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/**/*"]
}
Create a typescript file inside src directory
mkdir -p src && touch src/index.ts
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!");
After fixing the TypeScript errors run pnpm build
which will create a dist folder with js files inside