TypeScript – Get Started

前言

我学 TypeScript 的时候是 Angular 2.0 beta 的年代... 现在 Angular 都快 14 了.

但由于已经有 1 年半没有写 Angular 和 TypeScript 了, 所以特地写来复习 warm up 一下, 也把这些年零零散散的知识集中写一下做个记入.

 

参考

Youtube – TypeScript Tutorial 1 – 21 非常简单的入门

Youtube – TypeScript Course for Beginners - Learn TypeScript from Scratch! 前半段是简单入门, 后半段的 config 值得看看.

Youtube – Typescript tsconfig tutorial 教 tsconfig

 

开发工具

Node.js

VS Code

Live Server (VS Code Plug-in)

前端开发少不了上面 3 个, 就不多介绍了

 

安装

创建项目

mkdir play-typescript
cd play-typescript
yarn init

安装 typescript

npm install typescript --global
yarn add typescript --dev

一个全局, 一个本地. compile 会以本地的为标准, 全局的目的是要它的 command

 

Compile & Run

打开 VS Code, 创建 index.html 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./index.js" defer></script> <!-- 关键 -->
  </head>
  <body></body>
</html>

创建 index.ts

const h1 = document.createElement("h1");
h1.appendChild(document.createTextNode("Hello World"));
document.body.appendChild(h1);
View Code

运行命令

tsc index.ts

然后就会看见 index.js 被编辑出来了.

运行 Live Server

效果

这个就是最最最基本的使用方式

 

Problem with Import Module

参考: stackoverflow – How to use typescript in browser?

创建 index2.ts, export function

export function appendHelloWorld() {
  const h1 = document.createElement("h1");
  h1.appendChild(document.createTextNode("Hello World"));
  document.body.appendChild(h1);
}

在 index.ts, import 这个方法

import { appendHelloWorld } from "./index2";

appendHelloWorld();

在 index.html 的 script 加上 type="module". 要使用 import 关键字, html script 必须加上 type=module 哦

<script type="module" src="./index.js" defer></script>

运行命令 

tsc index.ts

compiled js

虽然 index 和 index2 都成功 compile 成了 js, 但是它默认使用的 module 方式是 CommonJS 的 (这个是给 Node.js 用的)

如果运行 index.html 的话会看见 error "exports is not defined"

修改 tsconfig 的 module, 运行命令

tsc index.ts --module es2015

module 的默认是 CommonJS 所以不可以用在 browser enviroment, browser 必须用 module es2015 也就是 es6 或以上.

这时运行 index.html 会看见 404 error

这是因为 import index2 的路径没有 file extension. 它是一个大 issue 来的:

Github – Compiled JavaScript import is missing file extension

Github – Compiled JavaScript import is missing file extension (Working as Intended)

Typescript 的原则是 JS 语句一定可以跑, 而 import { appendHelloWorld } from './index2' 对 Typescript 来说是 js 语句, 所以它不会去添加 extension. 反而要求写的时候一定要放 .js

如果你用 webpack 之类的打包工具, 它就会处理这些. 但如果没有, 那么 import 一定要声明 .js

在 index.ts 的 import 加上 index2.js, 这样就可以了.

 

进阶

上面这个 get started 只能用在非常简单的单元测试上. 如果想依赖一些 library 的话, 上面是不够用的. 

所以我又写了一篇进阶版本 : 

不过这个版本依然只是用于单元测试哦, 前端正式开发的话还是需要 bundler 的, 想了解可以看这篇: Webpack 学习笔记

 

posted @ 2022-04-28 21:49  兴杰  阅读(78)  评论(0编辑  收藏  举报