Typescript Basic Configurations: Understand tsconfig.json basics.
Typescript Basic Configurations: Set up a simple TypeScript project and understand tsconfig.json basics.
Set up a simple TypeScript project and understand tsconfig.json basics.
1. Install TypeScript
First, ensure you have Node.js and npm installed. Then, install TypeScript globally:
npm install -g typescriptAlternatively, for a specific project, install TypeScript locally in the project folder:
npm install --save-dev typescript2. Initialize a New Project
Create a new directory for your project, navigate into it, and initialize a tsconfig.json file:
mkdir my-typescript-project
cd my-typescript-project
tsc --init3. Understanding tsconfig.json
The tsconfig.json file is the configuration file for TypeScript. It controls how TypeScript compiles .ts files. Here's a breakdown of some of the key options:
Essential tsconfig.json Options
compilerOptions: This section controls the TypeScript compiler's settings.target: Specifies the JavaScript version TypeScript should output. Common values are:"target": "ES5" // Transpiles to ECMAScript 5 (widely supported)
"target": "ES6" // ECMAScript 2015module: Determines the module system for output files. Common values:"module": "commonjs" // For Node.js projects
"module": "es6" // For frontend (modern browsers)outDir: Specifies the output directory for compiled JavaScript files."outDir": "./dist"rootDir: Sets the root directory for TypeScript files."rootDir": "./src"strict: Enables strict type-checking options, ensuring safer code."strict": trueesModuleInterop: Enables compatibility between CommonJS and ES6 modules."esModuleInterop": true
includeandexclude:include: Specifies files/directories to be included in the project.exclude: Excludes files/directories from compilation.
Example:
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
4. Sample tsconfig.json
Here’s a minimal tsconfig.json setup:
5. Create a Simple TypeScript File
Inside the src directory, create an index.ts file:
6. Compile and Run
To compile your TypeScript code, run:
tscThis generates JavaScript files in the dist folder (as per outDir in tsconfig.json). To execute the compiled JavaScript file:
node dist/index.js7. Additional Configuration Options
As you expand, you may explore other options like:
allowJs: Allows JavaScript files to be compiled.sourceMap: Generates.mapfiles, helpful for debugging.