01安装和配置文件
# 安装和配置文件
浏览器是识别不了ts,所以上线前ts会转换成js
- npx和npm有什么关系?
npx最新的npm语法
1
# 0、初始化npm
npm init -y
1
# 1、安装typescript
npm i typescript -D
1
# 2、新建index.ts后缀文件
let num: number = "hello ts";
console.log(num);
1
2
2
# 3、编译ts文件
tsc index.ts//mac
npx tsc index.ts//windows
1
2
3
2
3
# 4、自动编译ts文件
- vscode 使用命令行tsc –init 生成tsconfig.json配置文件
tsc --init//mac
npx tsc --init//windows
1
2
3
2
3
- tsc –init 生成tsconfig.json配置文件,然后在终端运行 tsc -w
tsc -w//mac
npx tsc -w//windows
1
2
3
2
3
# 5、在package.json中配置
"scripts": { "serve":"tsc -w"}
1
tsconfig.json配置文件
{
"compilerOptions": {
"target": "es5", // 指定 ECMAScript 目标版本: 'ES5' 'es2015'
"module": "commonjs", // 指定使用模块: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
"moduleResolution": "node", // 选择模块解析策略
"experimentalDecorators": true, // 启用实验性的ES装饰器
"allowSyntheticDefaultImports": true, // 允许从没有设置默认导出的模块中默认导入。
"sourceMap": true, // 把 ts 文件编译成 js 文件的时候,同时生成对应的 map 文件
"strict": true, // 启用所有严格类型检查选项
"noImplicitAny": true, // 在表达式和声明上有隐含的 any类型时报错
"alwaysStrict": true, // 以严格模式检查模块,并在每个文件里加入 'use strict'
"declaration": true, // 生成相应的.d.ts文件
"removeComments": true, // 删除编译后的所有的注释
"noImplicitReturns": true, // 不是函数的所有返回路径都有返回值时报错
"importHelpers": true, // 从 tslib 导入辅助工具函数
"lib": ["es6", "dom"], // 指定要包含在编译中的库文件
"typeRoots": ["node_modules/@types"],
"outDir": "./dist", //打包过的目录
"rootDir": "./src", //打代码的目录
"baseUrl": ".", //基本地址为根目录
"paths":{
"@/*": ["src/*"] //路径别名
}
},
"include": [ // 需要编译的ts文件一个*表示文件匹配**表示忽略文件的深度问题
"./src/**/*.ts"
],
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
编辑 (opens new window)
上次更新: 2023/08/06, 00:38:41