确定模块系统


¥Determining module system

Node.js 在 TypeScript 文件中支持 CommonJSES 模块 语法。Node.js 不会从一个模块系统转换为另一个模块系统;如果你希望代码作为 ES 模块运行,则必须使用 importexport 语法,如果你希望代码作为 CommonJS 运行,则必须使用 requiremodule.exports

¥Node.js supports both CommonJS and ES Modules syntax in TypeScript files. Node.js will not convert from one module system to another; if you want your code to run as an ES module, you must use import and export syntax, and if you want your code to run as CommonJS you must use require and module.exports.

  • .ts 文件将由其模块系统确定 .js 文件相同。 要使用 importexport 语法,请将 "type": "module" 添加到最近的父级 package.json

    ¥.ts files will have their module system determined the same way as .js files. To use import and export syntax, add "type": "module" to the nearest parent package.json.

  • .mts 文件将始终作为 ES 模块运行,类似于 .mjs 文件。

    ¥.mts files will always be run as ES modules, similar to .mjs files.

  • .cts 文件将始终作为 CommonJS 模块运行,类似于 .cjs 文件。

    ¥.cts files will always be run as CommonJS modules, similar to .cjs files.

  • .tsx 文件不受支持。

    ¥.tsx files are unsupported.

与 JavaScript 文件一样,import 语句和 import() 表达式中的 文件扩展名是强制性的import './file.ts',不是 import './file'。由于向后兼容,文件扩展名在 require() 调用中也是强制性的:require('./file.ts'),而不是 require('./file'),类似于 .cjs 扩展在 CommonJS 文件中的 require 调用中是必需的。

¥As in JavaScript files, file extensions are mandatory in import statements and import() expressions: import './file.ts', not import './file'. Because of backward compatibility, file extensions are also mandatory in require() calls: require('./file.ts'), not require('./file'), similar to how the .cjs extension is mandatory in require calls in CommonJS files.

tsconfig.json 选项 allowImportingTsExtensions 将允许 TypeScript 编译器 tsc 使用包含 .ts 扩展名的 import 说明符对文件进行类型检查。

¥The tsconfig.json option allowImportingTsExtensions will allow the TypeScript compiler tsc to type-check files with import specifiers that include the .ts extension.