js-web的js工程改造成ts
js-web的js工程改造成ts
前篇
- a
步骤
安装 TypeScript 编译器
首先,需要安装 TypeScript 编译器。你可以使用 npm 安装 TypeScript:1
$ npm install -g typescript
cd 到项目, 创建 tsconfig.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21$ npm install typescript --save-dev
$ tsc --init
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"strict": false,
"outDir": "./js", // 指定编译后的输出目录
"rootDir": "./src", // 指定源代码的根目录
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
},
"include": [
"src/**/*" // src 的所有文件
],
"exclude": [
"node_modules"
]
}done. 测试
在 src 下创建 test.ts
1
2
3function add(a: number, b: number): number {
return a + b;
}使用命令生成 js
1
$ tsc
就会在 js 目录生成对应的 js 文件
全局声明
用于定义全局变量, 类型 等, 比如定义第三方库
在 src 目录下创建 types 目录, 里面在创建各种 xxx.d.ts 声明文件, 如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17// 三方库
declare var ClipboardJS: any;
declare var VConsole: any;
// window
interface Window {
[key: string]: any;
// itsonelink: typeof onelink; // 这里声明 window.itsonelink 为 onelink 类
}
interface ItsCfg {
getCfg?: (number) => IPlatCfg
}
// window 属性
declare var itscfg: ItsCfg;
declare var itsonelink: typeof onelink; // 定义为类, 就能直接访问静态方法就可以在 ts 中使用这些全局变量
1
2
3
4
5
6
7
8
9
10var cfg = itscfg.getCfg(platId)
var clipboard = new ClipboardJS("#copy", {
text: function (trigger) {
return txt;
}
});
window.rmg_args[key]
web app 注意事项
script 标签引入的三方库
例如 剪贴板库, html 中引入
1
<script src="../js/clipboard.min.js" type="text/javascript" charset="utf-8"></script>
想要在 ts 中使用避免错误检查的话, 则需要 全局声明
监听文件修改自动编译 js
在项目根目录输入命令
1
$ tsc --watch