官术网_书友最值得收藏!

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.

  1. 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;
}
}
  1. 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
  1. 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.

主站蜘蛛池模板: 资中县| 贵州省| 阿鲁科尔沁旗| 鄱阳县| 安乡县| 大竹县| 沾益县| 六盘水市| 天柱县| 平阴县| 瑞安市| 许昌市| 法库县| 哈密市| 苍溪县| 长泰县| 疏附县| 遂平县| 康乐县| 拉萨市| 新郑市| 固原市| 衡南县| 阿尔山市| 资中县| 裕民县| 高平市| 新建县| 六枝特区| 柯坪县| 张家川| 长岭县| 德安县| 揭东县| 武陟县| 邵武市| 三明市| 剑阁县| 尼玛县| 博乐市| 武功县|