Avatar ·

理解 tsconfig.json 中的 esModuleInterop:如何修复 TypeScript 中 CommonJS 模块的导入

大家好!我是 TypeScript 新手,在配置项目时遇到了一个我不理解的问题。我有一个 Node.js 项目,使用了流行的库 `express`。我通过 npm 安装了它,也安装了类型(`@types/express`)。我的 `tsconfig.json` 文件是这样的: ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true } } ``` 当我尝试像这样导入 express 时: ```typescript import express from 'express'; ``` TypeScript 报错:`Module '"/path/to/node_modules/@types/express/index"' has no default export.` 或者类似 `This module is declared with 'export =' and can only be used with a default import when using the 'esModuleInterop' flag.` 我读过关于 `esModuleInterop` 标志的内容,但不太理解它的作用以及为什么这会是问题。为什么我不能像在 JavaScript 中习惯的那样直接导入 express?