You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript导入Express报错及自定义模块与顶层await兼容问题求助

问题解决:TypeScript中ES模块、Node模块兼容及顶层await使用

项目文件结构

∟ src
  ∟ math
    ├ funcs.ts
    ├ constants.ts
    ├ index.ts
├ index.ts

初始正常代码(src/index.ts)

import * as math from './math/index.js';

console.log(`pi = ${math.PI}`);
console.log(`The area of a circle with radius 4 is ${math.circleArea(4)}`);

此时编译运行完全正常。

添加Express后的错误

更新src/index.ts代码为:

import express from 'express';
import * as math from './math/index.js';

console.log(`pi = ${math.PI}`);
console.log(`The area of a circle with radius 4 is ${math.circleArea(4)}`);

触发编译错误:

src/index.ts:1:21 - error TS2792: Cannot find module 'express'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?

当前配置文件

tsconfig.json

{
    "compilerOptions": {
        "outDir":"build",
        "target": "ES2022",
        "module": "ES2022"
    }
}

package.json

{
  "name": "typescript-lab",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc",
    "start": "npm run build && node ./build/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1",
    "typescript": "^4.7.4"
  }
}

核心困境

无法将tsconfig.json的module设为node,需同时满足:

  1. 正确导入自定义模块
  2. 在index.ts中使用顶层await
    但修改配置时总会触发以下问题之一:
  • 无法使用顶层await
  • 找不到/无法导入自定义模块
  • 无法导入Node模块(如express)

解决方案

1. 安装Express类型定义文件

Express本身无内置TypeScript类型,需补充安装类型包:

npm install -D @types/express

2. 调整tsconfig.json配置

保留module: "ES2022"以支持顶层await,同时添加Node模块解析相关配置:

{
    "compilerOptions": {
        "outDir": "build",
        "target": "ES2022",
        "module": "ES2022",
        "moduleResolution": "node",
        "esModuleInterop": true,
        "skipLibCheck": true
    },
    "include": ["src/**/*"]
}
  • moduleResolution: "node":让TypeScript按Node.js规则解析第三方包
  • esModuleInterop: true:解决CommonJS与ES模块的兼容性,允许默认导入CommonJS模块
  • skipLibCheck: true:跳过类型库检查,避免不必要的类型冲突

3. 验证自定义模块导入

保持自定义模块的导入路径为./math/index.js(带.js后缀),这是Node.js ES模块的强制要求,TypeScript编译后会保留正确路径,不影响运行。

4. 测试顶层await

现在可直接在src/index.ts中使用顶层await,示例:

import express from 'express';
import * as math from './math/index.js';

const app = express();
const port = await Promise.resolve(3000); // 顶层await示例

console.log(`pi = ${math.PI}`);
console.log(`The area of a circle with radius 4 is ${math.circleArea(4)}`);

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

5. 运行验证

执行npm run start,应能正常编译并运行,输出pi值、圆面积及服务器启动信息。


内容的提问来源于stack exchange,提问作者K09P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:52:13