====== 创建Typescript项目 ======
{{tag>node typescript}}
**1、创建文件夹**
直接创建typescipt文件夹
通过终端创建typescript文件夹
mkdir typescript
cd typescript
**2、进入typescript文件夹,初始化npm**
npm init
根据提示回车,这时候文件夹中会生成package.json文件。
===== 配置项目 =====
**3、安装typescript/tslint和NodeJS的类型声明**
npm install --save-dev typescript tslint @types/node
tslint是代码规则检查工具,保持代码风格一致。这时候文件夹中就会生成node_modules文件夹
**4、配置tsconfig.json**
{
"compilerOptions": {
"lib": ["ES2015"],
"module": "commonjs",
"outDir": "dist",
"sourceMap": true,
"strict": true,
"target": "es2015"
},
"include": [
"src"
]
}
可以自己新建并配置,或者使用命令初始化,处于typescript目录下,运行以下命令
''%%./node_modules/.bin/tsc --init%%''
基本配置项目说明:
* include ts文件在哪个文件夹中
* lib 运行环境包括哪些api
* module ts代码编译成什么模块系统
* outDir 编译后的js代码存放位置
* stirct 是否开启严格模式
* target ts编译成js的标准
* ... 有很多配置项具体可以查看其它资料
**5、配置tslint.json**
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {},
"rules": {
"no-console": false
},
"rulesDirectory": []
}
可以自己新建并配置或者使用命令初始化,处于typescript目录下,运行以下命令
''%%./node_modules/.bin/tslint --init%%''
===== 编写&运行代码 =====
**6、在src目录中创建index.ts文件并输入内容**
mkdir src
touch src/index.ts
现在整体目录如下
typescript
----node_modules/
----src/
----index.ts
----package.json
----tsconfig.json
----tslint.json
index.ts
...
console.log("hello TypeScript")
**7、编译**
''%%./node_modules/.bin/tsc%%''
这时候文件夹中就会生成 dist/index.js
**8、运行**
''%%node ./dist/index.js%%''
如果中断输出“hello Typescript"那么说明我们第一个typescript项目配置成功
===== 编译错误 =====
**包依赖错误**
Typescript 版本 ''%%tsc -v%%''
查看node对当前Typescript版本的依赖 ''%%npm dist-tags @types/node%%''
更新@types/node版本:如当前 tsc 为 3.6,对应的 @types/node 版本为 4.2.21\\
运行 ''%%npm i @types/node@4.2.21%%''
===== template =====
拉取 template 项目 ''%%git clone ssh://git@serverpi:/home/git/repository/npmTemplate.git%%''
删除 .git 目录,参考 [[it:server:git服务器|]] 重新上传一个新的项目