确定模块系统
【Determining module system】
Node.js 在 TypeScript 文件中同时支持 CommonJS 和 ES 模块 语法。Node.js 不会将一种模块系统转换为另一种;如果你希望代码以 ES 模块运行,必须使用 import 和 export 语法;如果你希望代码以 CommonJS 运行,则必须使用 require 和 module.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文件相同的方式。。要使用“import”和“export”语法,请在最近的父 “package.json” 后添加 “type”: “module”“。 .mts文件将始终作为 ES 模块运行,类似于.mjs文件。.cts文件将始终作为 CommonJS 模块运行,类似于.cjs文件。- 不支持
.tsx文件。
就像在 JavaScript 文件中一样,import 语句和 import() 表达式中也需要写文件扩展名:import './file.ts',而不是 import './file'。由于向后兼容,require() 调用中也必须包含文件扩展名:require('./file.ts'),而不是 require('./file'),这类似于在 CommonJS 文件中,require 调用必须包含 .cjs 扩展名。
【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 扩展名的文件的类型。
【The tsconfig.json option allowImportingTsExtensions will allow the
TypeScript compiler tsc to type-check files with import specifiers that
include the .ts extension.】