by hussein jabbar 2024
Install Node.js: Make sure you have Node.js installed. You can download it from the official website.
- Initialize a new Node.js project:
mkdir my-node-project
cd my-node-project
npm init -y
- Install TypeScript and necessary tools:
npm install typescript ts-node @types/node --save-dev
- Create a tsconfig.json file: This file will configure the TypeScript compiler options.
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src"],
"exclude": ["node_modules"]
}
- Create a simple TypeScript file: Create a directory named src and add a file named index.ts with the following content:
const sayHello = (name: string): string => {
return `Hello, ${name}!`;
};
console.log(sayHello("World"));
- Run the TypeScript file: You can use ts-node to run TypeScript files directly.
npx ts-node src/index.ts
- Compile TypeScript to JavaScript: To compile the TypeScript files to JavaScript, use the TypeScript compiler:
npx tsc
This will generate JavaScript files in the dist directory as specified in tsconfig.json.
- Run the compiled JavaScript:
node dist/index.js
. Linting: Use ESLint with TypeScript for code quality.
npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
. Create a .eslintrc.json file:
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"]
}
. Testing: Use a testing framework like Jest with TypeScript support.
npm install jest ts-jest @types/jest --save-dev
npx ts-jest config:init
Build Automation: Use tools like npm scripts or Gulp for automating tasks.
By following these steps, you will set up a Node.js project with TypeScript, enabling you to leverage TypeScript's type safety and advanced features while building server-side applications with Node.js.