TS中的模块
概述
两个模块之间的关系是通过在文件级别上使用import 和export 建立的 模块使用模块加载器 去导入其他的模块 在运行时,模块加载器的作用时在执行此模块代买钱去查找并执行这个模块的所有依赖,js模块加载器是服务于Node.js的CommonJS 和服务于Web应用的Require.js
模块导出
// 文件名 SomeInterface.ts
export interface SomeInterface {
代码部分
}
模块导入
另一个文件要使用该模块就需要使用import关键字 来导入,语法如下:
import someInterfaceRef = require("./SomeInterface")
JS、node和TS中模块的导入导出
JS中的模块导入导出
JS默认的导入导出
export default XXX
import xxxx from "路径"
JS按需导入和导出
export XXX
import { XXX } from "路径"
node中的模块
语法
exports.xxx = xxx
const xxx = require("path")
const {XX,XX} = require("path")
module.exports.xxx = xxx
const xxx = require("path")
const {xx,xx} = require("path")
TS中的模块
默认情况下在JS中 是不兼容上面两种导入方式混合使用,而TS中 对他们做了兼容
export interface IPerson {
name: string
age: number
sex: boolean
show ( ) : void
}
export const obj = {
name: "富甲一方钱七"
}
import Test = require ( "./mpduleTest" )
class UserInfo implements Test . IPerson{
name = "法外狂徒张三"
age = 18
sex = true
show ( ) {
console . log ( '法外狂徒' )
}
}
let person = new UserInfo ( )
console . log ( person. name)
import { obj} from "./mpduleTest"
console . log ( obj. name)
TS中的命名空间
TS中的命名空间概述
在TS1.5之前被叫做内部模块 ,主要用于组织代码,避免命名冲突 本质就是定义一个大对象 ,把变量 /方法 /类 /接口 …都放在里面 通过export 导出 通过namespace 定义
TS中的命名空间演示
export namespace D {
export const d = 230 ;
}
namespace A {
export const a = 10
}
console . log ( A . a)
namespace B {
export const b = 200 ;
export namespace C {
export const c = 12
}
}
console . log ( B . b)
console . log ( B . C . c)
import c = B . C . c
console . log ( c)
import { D } from "./namespaceTest"
console . log ( D . d)
三斜杠语法
三斜杠语法概述
三斜杠指令包含单个XML标签 的单行注释 ,注释的内用会作为编译器指令使用 如果在一个命名空间在一个单独的typescript 文件中,则最应使用三斜杆///引用他 语法格式
namespace User{
export interface IName {
uname: string
}
}
const username: User. IName = {
uname: '法外狂徒张三'
}
声明合并
接口合并
interface ITest {
name: string
}
interface ITest {
age: number
}
class Per implements ITest {
name: string = '法外狂徒张三'
age: number = 18
}
let per = new Per ( )
console . log ( per. name, per. age)
interface ITest {
show ( value: number ) : number
}
interface ITest {
show ( value: string ) : number
}
const func: ITest = {
show ( value: any ) : number {
if ( typeof value == "string" ) {
return value. length
} else {
return value. toFixed ( )
}
}
}
命名空间合并
与接口 一样,若名称相同 则会进行合并 同名 的命名空间 中不能出现同名 的变量 、方法 等
namespace ITest {
export const num = 10
}
namespace ITest {
}
命名空间 还可以和同名的类 /函数 /枚举 合并:
命名空间与类 的合并:1. say会被放在prototype上 2.类必须定义在命名空间的前面
class Perso {
say ( ) : void {
console . log ( "say hello" )
}
}
namespace Perso {
export const hi = ( ) : void => {
console . log ( "say Hi" )
}
}
console . dir ( Perso)
命名空间和函数 合并: 函数必须定义在命名空间的前面
function getCounters ( ) {
getCounters. count++ ;
console . log ( getCounters. count)
}
namespace getCounters {
export let count: number = 0
}
getCounter ( )
enum Gender{
Male,
Female
}
namespace Gender{
export const money: number = 18
}
console . log ( Gender)