一、TypeScript中使用其他Javascript库。
要想描述非TypeScript编写的类库的类型,我们需要声明类库所暴露的AIP
我们叫它声明因为大不是“外部程序”的具体实现。他们同事是 *.d.ts文件里定义的。
1.外部模块的声明别写 (略)
2.声明的引用,使用三斜杠指令
/// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://www.typescriptlang.org");
3.重点说一下,第三方库TypeScript的申明的使用,更多参考: VS Code智能提示功能之Typings
二、以JQuery为例,在Request.Js中使用
1.使用typings命令,安装JQuery的声明
typings install dt~jquery--global --save
安装结果:
常用的JQuery库如下:
2.在TypeScript使用使用
export class showOne {
name: string = '张三丰';
show() {
//这里的this仅对当前作用域转换,对应转换
//对于回调函数或事件中的this,并没有进行转换
$('#name').text(this.name);
$('#name').click(function () {
console.info(this);
// alert(this.name);
alert($(this).text());
});
}
}
3.生成模块的使用
//在模块中使用JQuery
require.config({
baseUrl: '../out',
deps: [
'../lib/jquery-1.11.3.min'
]
});
require(['test1'], function (test1) {
//console.info(test1.showOne);
var showOne = new test1.showOne();
showOne.show();
console.log(showOne.name);
});
三、创建模块结构指导
1.尽可能得在顶层导出
用户应该更容易地使用你模块导出内容。嵌套层次过多会变得那一处理。
从你的模块中导出一个命名空间就是一个增加嵌套的例子。虽然命名空间有时候有它们的用处。
2.如果仅导出单个 class 或 function,使用 export default
export default class SomeType {
constructor() { ... }
}
3.如果要导出多个对象,就把他们放在顶层导出
export class SomeType { /* ... */ }
export function someFunc() { /* ... */ }
4.明确的列出导入的名字
import { SomeType, SomeFunc } from "./MyThings";
let x = new SomeType();
let y = someFunc();
5.使用命名空间导入模式,当你要导出大量内容的时候
export class Dog { ... }
export class Cat { ... }
export class Tree { ... }
export class Flower { ... }
导入
import * as myLargeModule from "./MyLargeModule.ts";
let x = new myLargeModule.Dog();
6.使用重新导出进行扩展
你可能经常需要去扩展一个模块的功能。 JS里常用的一个模式是JQuery那样去扩展原对象。 如我们之前提到的,模块不会像全局命名空间对象那样去 合并。 推荐的方案是 不要去改变原来的对象,而是导出一个新的实体来提供新的功能。
7.模块里不要使用命名空间
四、关于模块的编译器解析
参考:https://www.tslang.cn/docs/handbook/module-resolution.html
更多: