用ts(typescript)写东西有一段时间了,之前库文件的提示使用typings管理,国内访问非常慢项目集成也不太方便。ts 2.0提供了npm包的形式来安装语法提示库,使用国内npm mirror速度飞快。用一个示例项目进行说明:
创建项目
1 2 3 4 5
   | mkdir types_demo cd types_demo mkdir src mkdir app npm install typescript jquery @types/jquery --save-dev
   | 
 
配置
创建 types_demo/tsconfig.json 文件,内容如下:
1 2 3 4 5 6 7 8 9 10 11
   | {   "compilerOptions": {     "module": "commonjs",     "target": "es5",     "noImplicitAny": false,     "sourceMap": true,     "removeComments": false,     "sourceRoot": "src",     "outDir": "app"   } }
  | 
 
编辑 types_demo/package.json,添加以下内容:
1 2 3 4
   | "scripts": {   "watch": "tsc -w",   "compile": "tsc -p ." },
  | 
 
编码
创建 types_demo/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
   | <!DOCTYPE html> <html lang="zh-cn"> <head>   <meta charset="UTF-8">   <title>types demo</title> </head> <body>   <div id="test">     <ul>       <li>1</>       <li><a href="#">types demo</a></li>     </ul>   </div>   <script src="./node_modules/jquery/dist/jquery.min.js"></script>   <script src="./app/index.js"></script> </body> </html>
   | 
 
创建 src/index.ts
1 2 3 4 5 6
   | let test = function () {   let $a = $('#test li>a');   console.log($a.text()); }
  test();
  | 
 
查看效果
执行 npm run compile 编译ts文件到js,因为@types库已经有jquery的提示,编计不会报错。用浏览打开 index.html 代码正常运行,有console.log输出的内容。
说明
使用 @types 语法库至少需要 ts 2.0.10(2.0已支持但有bug)以上版本。更多关于 @types 的配置查看 https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types