To use TypeScript with Node.js, you’ll need to follow these steps:
1. **Install Node.js**: If you haven’t already, make sure to have Node.js installed on your system. You can download it from the official website: https://nodejs.org/
2. **Create a new Node.js project**: Open a terminal or command prompt and create a new directory for your project. Navigate to the directory and initialize a new Node.js project by running:
mkdir my-ts-node-project
cd my-ts-node-project
npm init -y
This will create a default ‘package.json‘ file for your project.
3. **Install TypeScript**: You can install TypeScript globally using the following command:
npm install -g typescript
Or locally in your project by running:
npm install --save-dev typescript
4. **Install @types/node**: This package contains type definitions for Node.js, which allows TypeScript to understand how to interact with Node.js APIs. Install it using the following command:
npm install --save-dev @types/node
5. **Create a tsconfig.json file**: This file configures the TypeScript compiler settings. Create a new ‘tsconfig.json‘ file in the root of your project and add the following configuration:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "dist",
"moduleResolution": "node"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
This configuration tells the TypeScript compiler to transpile the ‘.ts‘ files in the ‘src‘ directory into JavaScript files in the ‘dist‘ directory. It also specifies that the target JavaScript version should be ES6, and that the module system should use CommonJS (which is what Node.js uses).
6. **Create your TypeScript source files**: Create a new directory named ‘src‘ in your project root, and create a new TypeScript file, e.g., ‘index.ts‘ inside it. Add some code to the ‘index.ts‘ file:
const greet = (name: string): string => {
return `Hello, ${name}!`;
};
console.log(greet("TypeScript"));
7. **Add a build and start script**: In your ‘package.json‘ file, add a build script and a start script. The build script will transpile the TypeScript files, and the start script will run the transpiled JavaScript files:
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
8. **Build and run your TypeScript code**: In the terminal or command prompt, run the following commands to build and run your code:
npm run build
npm run start
This will transpile your TypeScript code into JavaScript, and then run the ‘dist/index.js‘ file using Node.js, resulting in the output: ‘Hello, TypeScript!‘
In conclusion, to use TypeScript with Node.js, you need to configure your project to use the TypeScript compiler to transpile your TypeScript code to JavaScript and then use Node.js to run the transpiled code.