Skip to content

命名空间

typescript
// 定义不同的命名空间
namespace Controller {
  export const foo = "foo";
  export class User {
    public a: string = "";
    public constructor() {
      this.a = "aaa";
    }
  }
}
namespace Model {
  export const foo = "bar";
  export class User {
    public b: string = "";
    public constructor() {
      this.b = "bbb";
    }
  }
}

console.log(Controller.foo);
console.log(Model.foo);
console.log(new Controller.User());
console.log(new Model.User());

// 嵌套结构
namespace Application {
  export namespace Controller {
    export namespace Middleware {
      export class CheckLogin {
        constructor(request: object, next: Function) {
          // ...
          console.info(request, next);
        }
      }
    }
  }
  export namespace Module {}
  export namespace View {}
}

console.log(Controller.foo);
console.log(Model.foo);
console.log(new Controller.User());
console.log(new Model.User());

const request = { isLogined: false };
const nextCallback = () => console.log("未登录");

console.info(
  new Application.Controller.Middleware.CheckLogin(request, nextCallback)
);

打包合并 && reference

typescript
// User.ts
namespace User {
  export const username = "tom";
}

// App.ts
document.body.innerHTML = "<h2>" + User.username + "</h2>";
  • 合并打包: 必须指定用到的文件
shell
tsc --outFile ./dist/app.js User.ts App.ts
  • reference: 无需指定用到的文件,只需要指定入口文件就行
typescript
// App.ts: 注意必须加上下面一行,并且是 3 个斜杠而不是注释
/// <reference path="User.ts">
document.body.innerHTML = "<h2>" + User.username + "</h2>";

// 然后执行合并打包命令: tsc --outFile ./dist/app.js App.ts

打包编译工具

Released under the MIT License.