TypeScript — hello world

发布于 2020-07-27  425 次阅读


TypeScript

TypeScript是JavaScript语言的超集,但是TypeScript官方没有自己的Runtime/VM,官方做的是提供了一个叫tsc的编译器,能够让你将TypeScript源代码,编译为JavaScript源代码,从而在浏览器/Node等环境中运行。

官方文档:

英文
http://www.typescriptlang.org/docs/home.html
中文
https://www.tslang.cn/docs/home.html

安装

在一个普通的JavaScript工程中,运行yarn add --dev typescript,安装过程就完成了。--dev选项是表示这个依赖只在开发和测试时期需要,在发布时是不需要的,使用该选项时,依赖会被加入到package.json中的devDependencies中,而不是dependencies。关于DEV依赖可以看https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file

编译

1、初始化typescript工程
一个工程想要使用typescript来编译,就必须生成一个tsconfig.json来告知tsc如何编译这个工程。使用yarn tsc --init可以生成一个tsconfig.json的文件,这个文件描述了如何编译typescript。下面的是一个示例,唯一修改了的地方是outDir和rootDir,修改了源代码的目录和编译生成的js目录。

{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module":"commonjs",               /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "outDir": "./out",                        /* Redirect output "structure to the directory. */
    "rootDir": "./src",                       /* Specify the root */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit */
  }
}

2、在src目录下写一个index.ts,再运行yarn tsc -d,就可以看到dist目录下生成了index.js和index.d.ts。

import moment from 'moment'

export function hello() {
  const now: string = moment().format()
  const myName: string = 'world'
  console.log(`hello ${myName}, now=${now}`)
}
hello()

yarn tsc -d
在out文件夹下 可以看见生成了文件index.js, index.d.ts

执行

运行node ./out/index.js,就可以看到效果了。

关于xxx.d.ts文件和@types/xxxx

再编译过程中,我们生成了一个index.d.ts,他的作用是为typescript提供类型信息,这样做的好处是,你能够通过typescript写代码,并再编译发布之后供js项目使用,但是如果是typescript项目使用你发布的代码,也能够继续获取类型信息。之后的开发中,我们还经常会安装@types/xxxx这种类似的依赖包,这些包其实也是仅仅提供.d.ts文件,因为早起存在很多使用纯js编写的代码,为了能够再ts项目中很好的复用那部分的代码,开发者编写了.d.ts提供了类型信息。

ts-node直接执行

yarn add --dev ts-node
然后运行yarn ts-node ./src/index.ts

VSCode中调试TypeScript

在Visual Studio Code中点击Debug->Start Without Debugging,初次点击,Visual Studio Code会提示找不到launch.json,并生成一个新的launch.json,编辑launch.json内容为以下内容

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "args": ["${relativeFile}"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector"
    }
  ]
}

保存之后,切换到要调试的文件,设置断点,点击Debug->Start Debugging,就可以调试了

参考


Go Big or Go Home