# 十七.模块和命名空间
前言
默认情况下,我们编写的大门处于全局命名空间中
# 1.模块
文件模块:如果在你的 TypeScript 文件的根级位置含有import或者export,那么它会在这个文件中创建一个本地的作用域
// a.ts 导出
exprot default 'aaa'
//index.ts 导入
import name from './a'
1
2
3
4
5
2
3
4
5
# 2.命名空间
命名空间可以用于组织代码,避免文件内命名冲突
- 命名空间的使用
export namespace zoo {
export class Dog {
eat() {
console.log("zoo dog")
}
}
}
export namespace home {
export class Dog {
eat() {
console.log("home dog")
}
}
}
let dog_of_zoo = new zoo.Dog()
dog_of_zoo.eat()
let dog_of_home = new home.Dog()
dog_of_home.eat()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 命名空间嵌套使用
export namespace zoo {
export class Dog { eat () {
console.log('zoo dog')
}}
export namesapce bear{
export const name ='xxxx'
}
}
console.log(zoo.bear.name)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
命名空间中导出的变量可以通过命名空间使用