TS命名空间的使用和说明
作用
官方定义是作为内部模块标识使用。
在 TS 做模块化开发 过程中,可以参考如下规范(非必须):
- 内部模块:使用namespace
- 外部模块:对标 ES6等 模块语法
使用说明&案例参考
- 确认需要分离的代码
- 将分离的代码整合为独立文件,用
namespace #MODULENAME#标识出此模块的从属的主模块;并用export导出所需要被 外部使用的 变量或方法等。
⚠️注:只有属于 同一个namespace 的模块之间 才能正确 引用 —— 对应官方定义说明:此语法作为内部模块的声明
// product.model.ts
namespace App { //从属于App这个模块
export class Product { //导出此类
title: string;
price?: number;
constructor(t: string, p?: number) {
this.title = t;
this.price = p;
}
getInformation() {
return [this.title, `$${this.price ?? "N/A"}`];
}
}
}
- 在 主要逻辑处理文件 中使用
///和reference引入 独立模块
//app.ts
/// <reference path="./models/product.model.ts" />
import Product = App.Product; //该语法 与 import xx = require('xxx') 区分开,此处用法是对已有的符号创建简化别名
namespace App {
const products = [
{
title: "book",
price: 12.99,
},
{
title: "",
price: 699.99,
}
];
for (const pro of products) {
const loadedProducts = new Product(pro.title, pro.price);
console.log(loadedProducts.getInformation());
}
}
使用建议
由于namespace只是 TS语法,原生JS 不识别;因此TS的 编写编译过程 能正确识别相关代码;如果编译后的JS文件为 分离文件,运行时就无法识别各个模块之间的引用。
因此 想要使用namespace 进行 模块分离 需要确保 在 手动编译TS文件 或 使用自动化构建工具 时, 务必 输出&打包 为单个文件,如下是 tsconfig.json的 相关配置参考
"module": "amd"
"outFile": "./dist/bundle.js"