TypeScript is launched by Microsoft in 2012. Its purpose is the same as JavaScript, but it cannot be executed directly on browsers. It must be compiled into a JavaScript file before executed. TypeScript has many useful syntax, such as Object-Oriented and Generic, and static type definitions. When developing large projects, TypeScript is obviously better than JavaScript. For example, Angular uses TypeScript as the first language.
The complete code can be found in .
Table of Contents
Creating a Node.js Project with TypeScript
Create a Node.js project.
% mkdir TypeScriptExample % cd TypeScriptExample TypeScriptExample % npm init -y
Install TypeScript module.
TypeScriptExample % npm install --save-dev typescript
Create a TypeScript configuration file. Its default file name is tsconfig.json.
TypeScriptExample % vi tsconfig.json
Put the following JSON into tsconfig.json. include
refers to the code directory to be compiled. exclude
refers to the directory to be skipped by the compiler.
compilerOptions
refers to compiler settings. It has many options, which can be found in Compiler Options .
- module: Specify which module system to use in output JavaScript files. For example, ES6 uses import/export syntax.
- target: Specify what version of JavaScript to output.
- declaration: Whether the compiler should produce .d.ts declaration file.
- outDir: The destination of output.
- lib: The list of libraries to be included by the compiler. For example, including DOM library, the compiler will be able to recognize
window
anddocument
. - allowJs: Whether to allow the compiler to compile JavaScript files.
- moduleResolution: Specifies the Module Resolution.
- strict: Whether to enable all type checking options.
- experimentalDecorators: Whether to support ES Decorators .
{ "compilerOptions": { "module": "esnext", "target": "es6", "declaration": true, "outDir": "./lib", "lib": [ "esnext", "DOM" ], "allowJs": false, "moduleResolution": "node", "strict": true, "experimentalDecorators": true }, "include": [ "./src" ], "exclude": [ "node_modules" ] }
Add a TypeScrpt file called Person.ts.
TypeScriptExample % mkdir src TypeScriptExample % vi src/Person.ts
The code of Person.ts is simply as follows:
export class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } public toString(): string { return this.name + ' is ' + this.age + ' years old.'; } }
Add the compiler build command to the scripts of package.json.
{ "name": "TypeScriptExample", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "tsc" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "typescript": "^3.9.6" } }
Then execute the command to compile the project.
TypeScriptExample % npm run build
After compilation, the compiler will output the files under ./lib. You can see the compiled JavaScript files and the .d.ts declaration files.
TypeScriptExample % ls lib Person.d.ts Person.js
TSLint
TSLint is used to help us check whether our TypeScript syntax complies with coding rules. Let’s add TSLint to the project!
Install TSLint.
TypeScriptExample % npm install --save-dev tslint
Create a configuration file for TSLint. The default file name is tslint.json.
TypeScriptExample % vi tslint.json
There are many setting options for TSLint configuration file, which can be found in Configuring TSLint .
Put the following JSON into our tslint.json. It extends tslint:recommended coding rules. In addition, we add a rule of adding a semicolon at the end of each line.
{ "extends": "tslint:recommended", "rules": { "semicolon": { "options": [ "always" ] } } }
On line 11 in src/Person.ts, remove the semicolon at the end of the line. TSLint should raise an error for it.
export class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } public toString(): string { return this.name + ' is ' + this.age + ' years old.' } }
Put TSLint command into package.json. -p
tells TSLint where to find tsconfig.json.
{ "name": "TypeScriptExample", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "tsc", "lint": "tslint -p tsconfig.json" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "tslint": "^6.1.2", "typescript": "^3.9.6" } }
Execute TSLint command, you can see that it has found that there is syntax error. That is we just removed the semicolon at the end of the line.
TypeScriptExample % npm run lint > TypeScriptExample@1.0.0 lint /waynestalk/TypeScriptExample > tslint -p tsconfig.json /waynestalk/TypeScriptExample/src/Person.ts:11:57 ERROR: 11:57 semicolon Missing semicolon npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! TypeScriptExample@1.0.0 lint: `tslint -p tsconfig.json` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the TypeScriptExample@1.0.0 lint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! .npm/_logs/2020-07-08T04_51_16_291Z-debug.log
Webpack
Webpack is a JavaScript Bundle tool. If you don’t understand Webpack, this article has a detailed explanation.
We can let Webpack handle TypeScript by using ts-loader. Let’s take a look at how to integrate Webpack.
Install webpack, webpack-cli and ts-loader modules
TypeScriptExample % npm install --save-dev webpack webpack-cli ts-loader
Add webpack.config.js, and past the following the code. If you don’t understand the code below, please read the above Webpack tutorial first. There are two important parts in the code. One is extensions
where to set ts file extension. The other is to add ts-loader so that Webpack can process TypeScript files.
const path = require('path'); module.exports = { mode: 'production', entry: './src/Person.ts', output: { path: path.resolve(__dirname, 'dist'), filename: '[name].bundle.js', publicPath: '/', }, resolve: { extensions: ['.ts', '.tsx'], modules: ['node_modules'], }, module: { rules: [ { test: /\.ts(x?)$/, exclude: /node_modules/, use: [ { loader: 'ts-loader' } ] }, ] }, };
Finally, in package.json, change the tsc in npm run build to webpack. Use Webpack to compile instead.
{ "name": "TypeScriptExample", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack", "lint": "tslint -p tsconfig.json" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "ts-loader": "^7.0.5", "tslint": "^6.1.2", "typescript": "^3.9.6", "webpack": "^4.43.0", "webpack-cli": "^3.3.12", "wepack-cli": "0.0.1-security" } }
Execute the command and see what is different.
TypeScriptExample % npm run build > TypeScriptExample@1.0.0 build /TypeScriptExample > webpack Hash: 2fbb4aea58a915d46f3f Version: webpack 4.43.0 Time: 726ms Built at: 07/08/2020 10:07:19 PM Asset Size Chunks Chunk Names ../lib/Person.d.ts 135 bytes [emitted] main.bundle.js 1.07 KiB 0 [emitted] main Entrypoint main = main.bundle.js [0] ./src/Person.ts 194 bytes {0} [built]
Conclusion
If you have used TypeScript to develop, you will definitely love it. Although at the beginning, you want to give up because of static type definitions, but after getting used to it, you will find that static type definitions greatly improves code readability!