# vscode_ts **Repository Path**: lxc482113948/vscode_ts ## Basic Information - **Project Name**: vscode_ts - **Description**: No description available - **Primary Language**: TypeScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-04-18 - **Last Updated**: 2024-04-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TypeScript 自动编译示例项目 本项目演示了如何配置 `TypeScript` 自动编译,并且使用 `HTML` 文件引入编译后的 `JavaScript` 文件进行运行。 # 一、全局安装 ts ## 1、安装 ```js npm install -g typescript ``` ## 2、查安装是否成功 - 安装完成后,在控制台运行如下命令,检查安装是否成功: ```js tsc - V; ``` # 二、编写 TS 程序 ## 1、创建一个 ts 文件 ```js touch hello.ts ``` ## 2、编写代码 ```js // 定义一个变量 let a: number = 10; // 定义一个函数 function add(x: number, y: number): number { return x + y; } // 定义一个类 class Person { name: string; constructor(name: string) { this.name = name; } sayHello() { console.log(`Hello, ${this.name}!`); } } // 创建一个实例 const person = new Person('John'); person.sayHello(); ``` ## 3、运行程序 ```js // 编译 TS 文件 tsc hello.ts ``` ## 4、运行结果 - 这时候会生成一个编译好的文件 hello.js: ```js // 定义一个变量 var a = 100; // 定义一个类 var Person = /** @class */ (function () { function Person(name) { this.name = name; } Person.prototype.sayHello = function () { console.log('Hello, '.concat(this.name, '!')); }; return Person; })(); // 创建一个实例 var person = new Person('John'); person.sayHello(); ``` ## 5、运行编译后的文件 ```js node hello.js ``` ## 6、运行结果 ```js Hello, John! ``` > 这个时候其实已经完成了 `ts` 的基本运行、但是这样很累,每次写完 `ts` 代码想看结果的时候得先编译、再运行,这样就太麻烦了,所以我们需要一个`自动编译的配置`,只需要关注 `ts` 代码的编写,不用每次都编译,只需要运行 `ts` 文件即可。 # 三、自动编译 ## 1、配置自动编译 - 首先,在项目根目录下生成一个` tsconfig.json` 文件 ```js tsc --init ``` - 然后,在 `tsconfig.json` 文件中添加以下的配置,这样每次保存 `ts` 文件的时候,都会自动编译成 `js` 文件: ```json { "compileOnSave": true, // 保存时自动编译 "compilerOptions": { "target": "es5", "module": "commonjs", // 模块化规范 "strict": false, // 严格模式 "outDir": "./js" // 编译后的文件输出到 js 目录 } } ``` ## 2、启动监视 - 启动监视后,每次保存 `ts` 文件,都会自动编译成 `js` 文件: ```js tsc --watch ``` ## 3、编辑文件 - 根目录创建一个 `autoTest.ts` 文件,添加以下代码: ```js // 定义一个变量 let b: number = 10; console.log('b: ', b); ``` ## 4、保存文件 - 保存文件后,会自动编译成 `js` 文件: ## 5、运行结果 - 为啥方便查看已经编译好的 `js` 文件呢?每次使用 `node js/autoTest.js` 太麻烦所以我们创建一个 `index.html` 把自己当起写的文件引入进去 ```html Document ``` - 运行 `index.html` 即可在控制台看到结果 > 这样就完成了 `ts` 的基本运行,每次保存 `ts` 文件,都会自动编译成 `js` 文件,运行 `js` 文件即可 || 直接把当起自动编译成 `js` 文件引入到 `html` 中刷新当起的 `html` 页面控制台中查看结果。