Skip to content

husseinjabbar-2077/node.js-typescript

Repository files navigation

node.js-typescript

by hussein jabbar 2024

Setting Up a Node.js Project with TypeScript

Install Node.js: Make sure you have Node.js installed. You can download it from the official website.

  1. Initialize a new Node.js project:
mkdir my-node-project
cd my-node-project
npm init -y
  1. Install TypeScript and necessary tools:
npm install typescript ts-node @types/node --save-dev
  1. 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"]
}
  1. 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"));
  1. Run the TypeScript file: You can use ts-node to run TypeScript files directly.
npx ts-node src/index.ts
  1. 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.

  1. Run the compiled JavaScript:
node dist/index.js

Additional Tips

. 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.

About

Setting Up a Node.js Project with TypeScript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published