回帖:https://segmentfault.com/a/1190000018777683
2、初始化 NPM
在项目的根目录下,执行下面的命令:
npm init -y
现在项目结构如下:
ts3
├─dist
└─src
└─package.json
3、安装 TypeScript
在项目的根目录下,执行下面的命令:
npm i -g typescript
4、创建并配置 tsconfig.json
在项目的根目录下,执行下面的命令:
tsc --init
现在项目结构如下:
ts3
├─dist
└─src
└─package.json
└─tsconfig.json
在 tsconfig.json 中取消下面属性项的注释,并修改其属性的值:
这样设置之后,我们在 ./src 中编码 .ts 文件,.ts 文件编译成 .js 后,输出到 ./dist 中。
"outDir": "./dist",
"rootDir": "./src",
5、Hello Typescript
将下面代码复制到./src/index.ts中:
const hello: string = 'hello, Alan.Tang';
console.log(hello);
在项目的根目录下,执行下面的命令:
tsc 是编译命令,详情查看:https://www.tslang.cn/docs/handbook/typescript-in-5-minutes.html
tsc 的编译选项,详情查看:https://www.tslang.cn/docs/handbook/compiler-options.html
tsc
node ./dist/index.js
执行结果如下:
PS C:\Users\Alan\TestCode\ts3> tsc
PS C:\Users\Alan\TestCode\ts3> node ./dist/index.js
hello, Alan.Tang
6、使用自动实时编译
手动编译还是比较麻烦,如果能够保存代码后,自动编译就好了。
详情查看:https://go.microsoft.com/fwlink/?LinkId=733558
Ctrl + Shift + B 运行构建任务,将显示以下选项:
图片描述
选择 tsc: 监视 - tsconfig.json ,回车运行之后,编辑的代码保存之后,就会自动编译。
7、简化运行命令
每次输入 node ./dist/index.js 执行代码,有点麻烦,因为命令太长了。
在命令行界面,按键盘 ↑ 切换历史输入命令,可以快速使用历史输入过的命令。
三、代码检查
代码检查主要是用来发现代码错误、统一代码风格。
详情查看:https://ts.xcatliu.com/engineering/lint.html
1、安装 ESLint
ESLint 可以安装在当前项目中或全局环境下,因为代码检查是项目的重要组成部分,所以我们一般会将它安装在当前项目中。可以运行下面的脚本来安装:
npm install eslint --save-dev
由于 ESLint 默认使用 Espree 进行语法解析,无法识别 TypeScript 的一些语法,故我们需要安装 typescript-eslint-parser,替代掉默认的解析器,别忘了同时安装 typescript:
npm install typescript typescript-eslint-parser --save-dev
由于 typescript-eslint-parser 对一部分 ESLint 规则支持性不好,故我们需要安装 eslint-plugin-typescript,弥补一些支持性不好的规则。
npm install eslint-plugin-typescript --save-dev
现在项目结构如下:
ts3
├─dist
└─node_modules
└─src
└─package-lock.json
└─package.json
└─tsconfig.json
2、创建配置文件 .eslintrc.js
ESLint 需要一个配置文件来决定对哪些规则进行检查,配置文件的名称一般是 .eslintrc.js 或 .eslintrc.json。
当运行 ESLint 的时候检查一个文件的时候,它会首先尝试读取该文件的目录下的配置文件,然后再一级一级往上查找,将所找到的配置合并起来,作为当前被检查文件的配置。
在项目的根目录下,执行下面的命令:
创建配置文件
./node_modules/.bin/eslint --init
按需求,选择相应的选项:
您想如何使用ESLint?
? How would you like to use ESLint?
To check syntax, find problems, and enforce code style
您的项目使用什么类型的模块?
? What type of modules does your project use?
JavaScript modules (import/export)
您的项目使用哪个框架?
? Which framework does your project use?
None of these
你的代码在哪里运行?(按选择,切换所有,反转选择)
? Where does your code run? (Press to select, to toggle all, to invert selection)
Node
您想如何为您的项目定义一个样式?
? How would you like to define a style for your project?
Use a popular style guide
您想遵循哪种风格指南?
? Which style guide do you want to follow?
Airbnb (https://github.com/airbnb/javascript)
您希望配置文件的格式是什么?
? What format do you want your config file to be in?
JavaScript
Checking peerDependencies of eslint-config-airbnb-base@latest
您所选择的配置需要以下依赖项:
The config that you've selected requi

