Namespaces and namespace chunking in Typescript
Article Directory
namespace understanding
In the case of a large amount of code, in order to avoid conflicts in the naming of various variables, functions, classes, interfaces, etc. with similar functions can be placed in the namespace
The difference between namespaces and modules
Namespace : internal modules, mainly used to organize code and avoid naming conflicts
Module : the abbreviation of external module of ts, focusing on code reuse, there may be multiple namespaces in a module
Use of namespaces
<01 Single file usage.ts> file usage examples
namespace A {
interface Animal{
name:string;
eat():void;
}
export class Dog implements Animal {
//要加export才能用,否则联系不上对应的类
public name:string
constructor(name:string){
this.name = name
}
eat(){
console.log(`${
this.name} 吃肉骨头`)
}
}
export class Cat implements Animal{
public name:string
constructor(name:string){
this.name = name
}
eat(){
console.log(this.name+'今天想吃憨八哥')
}
work(){
console.log(this.name+'今天的工作是干饭')
}
}
}
namespace B {
interface Animal{
name:string;
eat():void;
}
export class Dog implements Animal {
public name:string
constructor(name:string){
this.name = name
}
eat(){
console.log(`${
this.name} 吃肉骨头`)
}
}
export class Cat implements Animal{
public name:string
constructor(name:string){
this.name = name
}
eat(){
console.log(this.name+'吃鱼')
}
work(){
console.log(this.name+'今天的工作是水群')
}
}
}
var c = new B.Cat('小花')
c.eat() //输出:小花吃鱼
var b = new A.Cat('修勾')
b.eat() //输出:修勾今天想吃憨八哥
Namespace chunking
If you want to use the namespace in this file in another ts file
(that is, you want to use the namespace of the <01 single file use.ts> file in the <02 other file import namespace.ts> file)
step one
It must be introduced in the <02 other files import namespace.ts> file
//02其他文件引入命名空间.ts内部
import {
A,B} from './dist/01单文件使用.js'
//就是import {你想要引入的命名空间} from '想要引入的命名空间的js文件路径'
var c = new B.Cat('小花')
c.eat() //输出:小花吃鱼
var b = new A.Cat('修勾')
b.eat() //输出:修勾今天想吃憨八哥
step two
And it should be exposed at the namespace inside the <01 single file using .ts> file
export namespace A {
其他和上面一样,唯独在namespace A前面加了export,将其暴露出去
}
export namespace B {
其他和上面一样,唯独在namespace B前面加了export,将其暴露出去
}