typescript 文档阅读笔记- modules

因为在 js、ts 中,每个文件就是一个 module,凡是通过 import 或者 require 对应的路径,都是一个 module。

export = and import = require()

// ZipCodeValidator.ts
let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
  isAcceptable(s: string) {
    return s.length === 5 && numberRegexp.test(s);
  }
}
export = ZipCodeValidator;
// Test.ts
import zip = require("./ZipCodeValidator");

Working with Other JavaScript Libraries

对于没有使用 ts 编写的第三方库,我们可以使用 .d.ts 文件。我们可以为每个 module 声明一个 .d.ts 文件。

// node.d.ts
declare module "url" {
  export interface Url {
    protocol?: string;
    hostname?: string;
    pathname?: string;
  }

  export function parse(
    urlStr: string,
    parseQueryString?,
    slashesDenoteHost?
  ): Url;
}

declare module "path" {
  export function normalize(p: string): string;
  export function join(...paths: any[]): string;
  export var sep: string;
}
--------------
import tool from 'Src/const/tool'
declare module 'Src/const/tool' {
	
}

Now we can /// <reference> node.d.ts and then load the modules

/// <reference path="node.d.ts"/>
import * as URL from "url";
let myUrl = URL.parse("http://www.typescriptlang.org");

如果我们不想对某个 modules 声明具体的类型,可以直接像下面这样:

declare module "hot-new-module"; // hot-new-module 中的任何导出的变量类型都是 any

import x, { y } from "hot-new-module"; //x: any, y: any

导入非 js module

除了可以导入 js,还可以导入图片、字体等,如下:

import imag from 'test.svg'

对于这些非 js module,可以像下面这样为其声明类型:

declare module "*.svg" {
  const content: string;
  export default content;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值