首页 > 解决方案 > 使用 Typescript 设置 Express 以使用顶级异步

问题描述

我正在尝试以一种可以在顶级模块中使用异步的方式设置我的环境,并使用在 server.ts 中看到的导入语句类型。

在 package.json 中使用type = module允许我这样做,但现在我遇到Cannot find module了 server.ts 中引起的错误

对此的解决方案应该是将 .ts 添加到导入的路径中,但这会导致未知类型异常。对此的修复应该是type=module从 package.json 中删除,但是我不能使用我想要的导入样式

感觉就像我在这里兜圈子

服务器.ts

...
import purchaseRoute from './routes/purchaseRoute';

const connection = await createConnection({
    type: "mssql",
    host: "localhost",
    username: "user",
    password: "password",
    database: "Investments"
});

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

包.json

{
  "name": "investments",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",

购买路由.ts

router.route('/').post(async(req, res) => {
    await getConnection()
        .createQueryBuilder()
        .insert()
        .into(Purchase)
        .values(req.body);
})
export default router;

标签: node.jstypescriptexpresspackage.jsontsconfig

解决方案


推荐阅读