目的:方便学习和实践的时候,查看简单代码的输出结果。
简单编译 ts 文件
-
npm install -g typescript全局安装TypeScript -
新建文件夹 Test
-
创建
test.ts文件,写入
const str: string = '12';
- 创建
tsconfig.json文件,不需要写入内容
综上文件夹结构为:
- Test
- test.ts
- tsconfig.json
- 打开终端,输入
tsc test.ts,运行文件进行编译 输出编译成功结果:
文件内容改成 const str: string = 1, 输出编译错误结果:
在浏览器打开并输出打印
在上一部分的基础上操作:
- 修改文件夹结构为
- Test
- src
- index.html
- index.ts
- tsconfig.json
tsconfig.json文件写入:
{
"compilerOptions": {
"outFile": "./build/page.js", /* 仅生成一个文件,在index.html中引入 */
"rootDir": "./src", /* ts文件位置目录 */
"outDir": "./build", /* 编译后js文件存放目录 */
}
}
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>
</head>
<body>
</body>
<!-- 引入编译的js文件 -->
<script src="../build/page.js"></script>
</html>
- 打开终端,输入
tsc --w,运行文件进行编译并在ts文件操作之后实时更新编译结果。
// index.ts
let tom: [string, number];
tom = ['12', 14]
console.log(tom);
编译结果:
控制台打印:['12', 14]
// index.ts
let tom: [string, number];
tom = ['12', 14, 1]
console.log(tom);
编译结果:
控制台打印:['12', 14, 1]