命名空间
TypeScript与ECMAScript 2015一样,任何包含顶级import或者export的文件都被当成一个模块。相反地,如果一个文件不带有顶级的import或者export声明,那么它的内容被视为全局可见的(因此对模块也是可见的)
namespace 所有的变量以及方法必须导出才能访问
用法:
namespace Test {
//变量 方法
}
命名空间中通过export将想要暴露的部分导出
如果不用export 导出是无法读取其值的
namespace a {
export const Time: number = 1000
export const fn = <T>(arg: T): T => {
return arg
}
fn(Time)
}
namespace b {
export const Time: number = 1000
export const fn = <T>(arg: T): T => {
return arg
}
fn(Time)
}
a.Time
b.Time
嵌套命名空间
namespace a {
export namespace b {
export class Vue {
parameters: string
constructor(parameters: string) {
this.parameters = parameters
}
}
}
}
let v = a.b.Vue
new v('1')
抽离命名空间
test.ts
export namespace Test{
export const a =12;
}
index.ts
import { Test } from "./test";
console.log(Test.a)
简化命名空间
namespace A {
export namespace B {
export const C = 1
}
}
import X = A.B.C
console.log(X);
合并命名空间
namespace test{
export const a =12
}
namespace test{
export const b =12
}
test.
模块
es6模块化规范用法
默认导出可以导出任意类型,这儿举例导出一个对象,并且默认导出只能有一个
引入的时候名字可以随便起
//导出
export default {
a:1,
}
//引入
import test from "./test";
分别导出
export default {
a:1,
}
export function add<T extends number>(a: T, b: T) {
return a + b
}
export let xxx = 123
//引入
import obj,{xxx,add} from './test'
重名问题
使用as重命名
import obj,{xxx as bbb,add} from './test'
console.log(bbb)
动态引入
import只能写在顶层,不能掺杂到逻辑里面,这时候就需要动态引入了
if(true){
import('./test').then(res => {
console.log(res)
})
}