[Typescript] 名前空間と ts の名前空間ブロック

Typescript の名前空間と名前空間のチャンク化

名前空間の理解

大量のコードの場合、さまざまな変数、関数、クラス、インターフェイスなどの名前の競合を避けるために、類似した関数を持つものを名前空間に配置できます。

名前空間とモジュールの違い

名前空間: 内部モジュール。主にコードを整理し、名前の競合を避けるために使用されます。

モジュール: ts の外部モジュールの略語。コードの再利用に重点を置き、モジュール内に複数の名前空間が存在する場合があります。

名前空間の使用

<01 単体ファイル使用.ts>ファイルの使用例

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()				//输出:修勾今天想吃憨八哥

名前空間のチャンク化

このファイルの名前空間を別の ts ファイルで使用する場合
(つまり、<01 単一ファイル use.ts> ファイルの名前空間を <02 他のファイル インポート名前空間.ts> ファイルで使用する場合)

第一歩

<02 other files import namespace.ts> ファイルに導入する必要があります

//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()				//输出:修勾今天想吃憨八哥

ステップ2

そして、<01 単一ファイルを使用した .ts> ファイル内の名前空間で公開する必要があります。

export namespace A {
    
    
其他和上面一样,唯独在namespace A前面加了export,将其暴露出去
}
export namespace B {
    
    
其他和上面一样,唯独在namespace B前面加了export,将其暴露出去
}

おすすめ

転載: blog.csdn.net/m0_63779088/article/details/126507614