JavaScript has a long history of different ways to handle modularizing code. TypeScript having been around since 2012, has implemented support for a lot of these formats, but over time the community and the JavaScript specification has converged on a format called ES Modules (or ES6 modules). You might know it as the import/export syntax.JavaScript有很长的历史,有不同的方式来处理模块化的代码。TypeScript从2012年开始出现,已经实现了对许多这些格式的支持,但随着时间的推移,社区和JavaScript规范已经趋于一种格式,称为ES模块(或ES6模块)。你可能知道它是导入/导出语法。

ES Modules was added to the JavaScript spec in 2015, and by 2020 had broad support in most web browsers and JavaScript runtimes.ES Modules在2015年被加入到JavaScript规范中,到2020年,在大多数网络浏览器和JavaScript运行时中都有广泛的支持。

For focus, the handbook will cover both ES Modules and its popular pre-cursor CommonJS module.exports = syntax, and you can find information about the other module patterns in the reference section under Modules.为了突出重点,本手册将涵盖ES模块和其流行的前驱CommonJS module.exports = 语法,你可以在模块下的参考部分找到其他模块模式的信息。

How JavaScript Modules are Defined如何定义JavaScript模块

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.在TypeScript中,就像在ECMAScript 2015中一样,任何包含顶级导入或导出的文件都被视为一个模块。

Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).相反,一个没有任何顶级导入或导出声明的文件被视为一个脚本,其内容可在全局范围内使用(因此也可用于模块)。

Modules are executed within their own scope, not in the global scope. This means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms. Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.模块在自己的范围内执行,而不是在全局范围内。这意味着在模块中声明的变量、函数、类等在模块外是不可见的,除非它们被明确地用某种导出形式导出。相反,要使用从不同模块导出的变量、函数、类、接口等,必须使用导入的形式将其导入。

Non-modules非模块

Before we start, it’s important to understand what TypeScript considers a module. The JavaScript specification declares that any JavaScript files without an export or top-level await should be considered a script and not a module.在我们开始之前,必须了解 TypeScript 认为什么是模块。JavaScript规范声明,任何没有导出或顶层等待的JavaScript文件都应该被认为是一个脚本而不是一个模块。

Inside a script file variables and types are declared to be in the shared global scope, and it’s assumed that you’ll either use the outFile compiler option to join multiple input files into one output file, or use multiple <script> tags in your HTML to load these files (in the correct order!).在一个脚本文件中,变量和类型被声明为在共享的全局范围内,并且假定你会使用outFile编译器选项将多个输入文件加入一个输出文件,或者在你的HTML中使用多个