- Learn React with TypeScript 3
- Carl Rippon
- 284字
- 2021-06-10 19:16:37
Configuring compilation
We need to compile our TypeScript code before it can be executed in a browser. We do this by running the TypeScript compiler, tsc, on the files we want to compile. TypeScript is very popular and is used in many different situations:
- It is often introduced into large existing JavaScript code bases
- It comes by default in an Angular project
- It is often used to add strong types to a React project
- It can even be used in Node.js projects
All these situations involve slightly different requirements for the TypeScript compiler. So, the compiler gives us lots of different options to hopefully meet the requirements of our particular situation.
- Let's give this a try by opening Visual Studio Code in a new folder and creating a new file, called orderDetail.ts, with the following content:
export interface Product {
name: string;
unitPrice: number;
}
export class OrderDetail {
product: Product;
quantity: number;
getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}
- We can open a Terminal in Visual Studio Code by going to the View menu and choosing Terminal. Let's enter the following command in the Terminal:
tsc orderDetail
- Hopefully, no errors should be output from the compiler and it should generate a file called orderDetail.js, containing the following transpiled JavaScript:
"use strict";
exports.__esModule = true;
var OrderDetail = (function () {
function OrderDetail() {
}
OrderDetail.prototype.getTotal = function (discount) {
var priceWithoutDiscount = this.product.unitPrice * this.quantity;
var discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
};
return OrderDetail;
}());
exports.OrderDetail = OrderDetail;
We'll continue to use orderDetail.ts in the following sections as we explore how the compiler can be configured.
推薦閱讀
- C# 2012程序設計實踐教程 (清華電腦學堂)
- PHP程序設計(慕課版)
- Learning Laravel 4 Application Development
- Corona SDK Mobile Game Development:Beginner's Guide(Second Edition)
- C語言程序設計上機指導與習題解答(第2版)
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(2)
- JavaScript應用開發實踐指南
- CodeIgniter Web Application Blueprints
- 深入解析Java編譯器:源碼剖析與實例詳解
- 關系數據庫與SQL Server 2012(第3版)
- Ubuntu Server Cookbook
- RESTful Web API Design with Node.js(Second Edition)
- Mastering Machine Learning with scikit-learn
- Implementing NetScaler VPX?(Second Edition)
- Unity AI Game Programming(Second Edition)