1、 新建工程:所用命令:
mkdir typescript(typescript是项目名称);
2、 初始化工程:确保已安装npm、typescript、typings、以及全局安装node的一些包:concurrently、lite-server已经安装。
npm init(会生成package.json文件);
{
"name": "typescript2","version": "1.0.0","description": "Learning TypeScript.","scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"","lite": "lite-server","tsc": "tsc","tsc:w": "tsc -w"
},"author": "2gua","license": "ISC","dependencies": {
},"devDependencies": {
"lite-server": "^2.2.0","concurrently": "^2.0.0"
}
}
3、 在根目录下创建ts和js文件夹,分别用来装ts和js文件;并在根目录下创建tsconfig.json文件:
在ts文件夹下创建第一个ts文件——t1.ts:
/**
* BirdWhisperer
* by 2gua
*/
class animals {
animal: string;
constructor(message: string) {
this.animal = message;
}
run() {
return '吃人的' + this.animal;
}
}
let a = new animals('老虎');
document.body.innerHTML = a.run();
在tsconfig.json中修改配置为:
{
"compilerOptions": {
"target": "es5","module": "amd","sourceMap": true,"outDir": "js" //编译后输出路径
},// "include":[
// "ts"
// ],"exclude": [ //排除设置哪些文件不被编译
"js","node_modules","typings/main","typings/main.d.ts"
]
}
创建index.html页面。页面引入将要生成的js文件。
4、 在命令行窗口进入项目根目录,执行npm start,会看到自动打开浏览器窗口,而且不需要刷新浏览器,它会自动刷新。同时,它也会执行编译生成js文件和js.map文件。
5、 点击debug按钮,选择node.js,此时会自动创建.vscode/launch.json文件,这里只需要修改program项的参数,如下:
"configurations": [
{
"name": "Launch","type": "node","request": "launch","program": "${workspaceRoot}/js/t1.js",