Typescript Tutorial
- Atul
- Programming
- September 5, 2023
Table of Contents
How to get started with Typescript
Prerequisites:
- Install Node.
1. Installing Typesript
npm install -g typescript
By running this command Typescript will be installed globally, now we need to link it.
npm link typescript
Check the version:
tsc --v
2. Compiling .ts files
- Create a file hello.ts with
let ss = "String";
let num = 45;
- Open up terminal
$ tsc hello.ts
This will watch for any changes and report any errors in code.
$ tsc hello.ts -w
- tsc will create .js file as an output.
This is how you install Typescript and run it.
3. Typescript Project
Create a dir and cd
into it
$ tsc --init
The above command will create a file called “tsconfig.json”
{
"compilerOptions": {
...
/* Modules */
"target": "es2016", // Change to "ES2015" to compile to ES6
"rootDir": "./src", // Where to compile from
"outDir": "./public", // Where to compile to (usually the folder to be deployed to the web server)
/* JavaScript Support */
"allowJs": true, // Allow JavaScript files to be compiled
"checkJs": true, // Type check JavaScript files and report errors
/* Emit */
"sourceMap": true, // Create source map files for emitted JavaScript files (good for debugging)
"removeComments": true, // Don't emit comments
},
"include": ["src"] // Ensure only files in src are compiled
}
Inside a React Project
Create a file called “tsconfig.json” in root dir of react project with the following contents.
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node",
}
}
Compiling with Webpack
npm install webpack webpack-cli ts-loader
Create a file called “webpack.config.js” in root dir with the following contents.
const path = require('path');
module.exports = {
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};