Hiển thị “Hello, World!” trong TypeScript

Code TypeScript hiển thị ‘Hello World’ trong node.js

  1. Đầu tiên hãy tạo một folder để lưu code, ví dụ folder là : helloworld .
  2. Chạy VS Code và mở folder đó .
  3. Tạo một file TypeScript gọi là app.ts với extension của file là .ts
  4. Thêm code bên dưới vào file app.ts
let message: string = 'Hello, World!';
console.log(message);
  1. Mở Terminal trong VS Code bằng keyboard shortcut Ctrl+` hoặc theo menu Terminal > New Terminal

Hiển thị “Hello, World!” trong TypeScript 6

  1. Gõ command bên dưới để compile(biên dịch) file app.ts:
tsc app.ts

Hiển thị “Hello, World!” trong TypeScript 7

Nếu mọi thứ ok, bạn sẽ thấy một file gọi là app.js được sinh ra bởi TypeScript compiler:
Hiển thị “Hello, World!” trong TypeScript 8

Để chạy tệp app.js trong node.js, bạn sử dụng lệnh sau:

node app.js

Output:

Hello, World!

Code TypeScript hiển thị ‘Hello World’ trong Web Browsers

  1. Đầu tiên, bạn tạo một file gọi là index.html và include file app.js như bên dưới:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TypeScript: Hello, World!</title>
</head>
<body>
    <script src="app.js"></script>
</body>
</html>
  1. Cập nhật code file app.ts như bên dưới:
let message: string = 'Hello, World!';
// create a new heading 1 element
let heading = document.createElement('h1');
heading.textContent = message;
// add the heading the document
document.body.appendChild(heading);
  1. Biện dịch file app.ts với command sau:
tsc app.ts
  1. Mở Live Server từ VS code bằng cách click chuột phải vào file index.html và select với Open with Live Server
    Hiển thị “Hello, World!” trong TypeScript 9

Live Server sẽ mở index.html với thông báo sau:
Hiển thị “Hello, World!” trong TypeScript 10

Để thực hiện các thay đổi, bạn cần chỉnh sửa tệp app.ts. Ví dụ:

let message: string = 'Hello, TypeScript!';

let heading = document.createElement('h1');
heading.textContent = message;

document.body.appendChild(heading);

Và biên dịch tệp app.ts:

tsc app.ts

Output với Live Server :

Hello, TypeScript!

TypeScript compiler sẽ sinh ra một file mới là app.js và Live Server sẽ tự động reload nó trên web browser.
Chú ý: file app.js là output file của file app.ts, do đó, bạn không bao giờ được trực tiếp thay đổi code trong tệp này, nếu không bạn sẽ mất các thay đổi sau khi biên dịch lại tệp app.ts.

Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *