命名空间和模块

这篇文章概述了在 TypeScript 中使用模块和命名空间来组织代码的各种方法。我们还将讨论如何使用命名空间和模块的一些高级主题,并解决在 TypeScript 中使用它们时的一些常见缺陷。

有关 ES 模块的更多信息,请参阅 模块 文档。有关 TypeScript 命名空间的更多信息,请参阅 命名空间 文档。

注意:在非常旧的 TypeScript 版本中,命名空间被称为 'Internal Modules',这些早于 JavaScript 模块系统。

使用模块

模块可以包含代码和声明。

模块还依赖于模块加载器(例如 CommonJs/Require.js)或支持 ES 模块的运行时。模块为捆绑提供了更好的代码重用、更强的隔离和更好的工具支持。

PZ1Rj+HhGGj/hKFN4MqX9v68QpnJgRv3ccritMeIw/nCO8eEkl+tD2bANXZrgpn10c0FqRXKepJWK6Q3uAPO5xKLH0zJWKSO0BuqAwWCS0DWD8XlRuJ/UZjnBHvqzG0JHYojBtwqDCdfaTZ4xyGdzORJAR7CjyS2amR6fwLgxOoPwCb/3yNb+asIyKB6RVrm

qThJf3AiCBJzpBRnLrEk7DuhbP15KArXafbT1NmSeN+v4FZowas0F/M+q2HbXjx5dMpdpv1CwiikzzuDHxqHvfbzwtsVxciwaoynOGXztrk2PFGwZyDo2A11m9CYkwAaTsrGW5InI//grqmwC9cojWLOFtuduxEV+SuBMGVZSArussYk/gHxQZG90NigilAimlxNO4rQjMVKFYPqHC3JXibJ5+j6p4HlU5YmSgVWbgI=

使用命名空间

SwKv8O02QaBvw7jkG1vq9JlZUz6ZPMTXIVolU3Qw+ecD/9Szzu5uAtB8c9hOjXCSa9U21D+K/05hdIJadaIkfpsgA9pFoYeoIS1rw6M4rchA7i2mGfKAiGPlzfG4yacem0LRsuTQjITp/Balfu9WzVbDU6FDg8NgsvjnluOVIvfgPMwdeMoIdCxcXXorhFohyGRCVkJLatXo8aB5uH+CmC4L3GWZCsXT933wLlMRuytu9savd/JArD1W4Zw3o3dF2bWi0PfRbIYku7fqZHhFVK87GFygLL4iz0p5U3doOdTir52bNxpxWgzOtdfF3BGQ+hAKo/iilH4Bo9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