How to setup a typescript project in vscode
Setting up a new TypeScript project involves several steps. Here's a step-by-step guide to get you started:
-
Install Node.js and npm: Ensure you have Node.js installed, which comes with npm (Node Package Manager). You can download and install Node.js from nodejs.org.
-
Create a new project directory:
mkdir my-typescript-project cd my-typescript-project
-
Initialize a new Node.js project: This creates a
package.json
file that keeps track of your project's dependencies and scripts.npm init -y
-
Install TypeScript: Install TypeScript as a dev dependency.
npm install typescript --save-dev
-
Initialize a TypeScript configuration file: Create a
tsconfig.json
file to configure the TypeScript compiler options.npx tsc --init
-
Edit
tsconfig.json
: Adjust the settings as needed. Here's an example configuration:{ "compilerOptions": { "target": "ES6", // Specify ECMAScript target version "module": "commonjs", // Specify module code generation "outDir": "./dist", // Redirect output structure to the directory "rootDir": "./src", // Specify the root directory of input files "strict": true, // Enable all strict type-checking options "esModuleInterop": true, // Enables emit interoperability between CommonJS and ES Modules "skipLibCheck": true, // Skip type checking of declaration files "forceConsistentCasingInFileNames": true // Disallow inconsistently-cased references to the same file } }
-
Create a source directory: Create a
src
directory for your TypeScript files.mkdir src
-
Add a sample TypeScript file: Create a sample TypeScript file in the
src
directory.// src/index.ts const greeting: string = 'Hello, TypeScript!'; console.log(greeting);
-
Compile the TypeScript code: Compile your TypeScript files into JavaScript using the TypeScript compiler.
npx tsc
-
Run the compiled JavaScript code: The compiled JavaScript files will be in the
dist
directory (as specified intsconfig.json
). Run the compiled code using Node.js.node dist/index.js
-
Add build scripts to
package.json
: Modify yourpackage.json
to add scripts for building and running your project.{ "scripts": { "build": "tsc", "start": "node dist/index.js" } }
Now you can build and run your project using:
npm run build npm start
-
Install additional dependencies (optional): Depending on your project needs, you might need other packages. For example, if you're working on a Node.js project, you might install types for Node.js:
npm install @types/node --save-dev