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 typescript
Alternatively, for a specific project, install TypeScript locally in the project folder:
npm install --save-dev typescript
2. 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 --init
3. 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": true
esModuleInterop
: Enables compatibility between CommonJS and ES6 modules."esModuleInterop": true
include
andexclude
: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:
{"compilerOptions": {"target": "ES6","module": "commonjs","outDir": "./dist","rootDir": "./src","strict": true,"esModuleInterop": true},"include": ["src/**/*"],"exclude": ["node_modules", "dist"]}
5. Create a Simple TypeScript File
Inside the src
directory, create an index.ts
file:
// src/index.tsconst greet = (name: string): string => `Hello, ${name}!`;console.log(greet("World"));
6. Compile and Run
To compile your TypeScript code, run:
tsc
This generates JavaScript files in the dist
folder (as per outDir
in tsconfig.json
). To execute the compiled JavaScript file:
node dist/index.js
7. Additional Configuration Options
As you expand, you may explore other options like:
allowJs
: Allows JavaScript files to be compiled.sourceMap
: Generates.map
files, helpful for debugging.