- 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.
推薦閱讀
- Boost程序庫完全開發指南:深入C++”準”標準庫(第5版)
- Microsoft Exchange Server PowerShell Cookbook(Third Edition)
- Python從小白到大牛
- 算法精粹:經典計算機科學問題的Java實現
- QGIS By Example
- Oracle GoldenGate 12c Implementer's Guide
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- Android移動應用開發項目教程
- Java高手是怎樣煉成的:原理、方法與實踐
- Python數據科學實踐指南
- 你好!Java
- Improving your Penetration Testing Skills
- Kotlin入門與實戰
- 軟件測試
- Java無難事:詳解Java編程核心思想與技術(第2版)