在 vercel 中编译 Typescript?

问题描述 投票:0回答:1

我在 vercel 上托管一个简单的整体 Web 应用程序。我已将代码迁移到 Typescript,因此该项目现在使用:Typescript、Mustache、ExpressJS、MySQL。问题是我无法让 vercel 编译打字稿。经过多次实验、阅读尽可能多的文档并调整和添加多个配置,现在这些是我的 .JSON 文件。

vercel.json

{
  "version": 2,
  "buildCommand": "npm install --include=dev && npm run build",
  "outputDirectory": "dist",
  "builds": [
    {
      "src": "dist/server.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/dist/server.js"
    },
    {
      "src": "/public/(.*)",
      "dest": "/public/$1"
    }
  ]
}

package.json

{
  "name": "my-website",
  "version": "1.0.0",
  "description": "Landing page of my website. Meant to serve as a portal to my projects",
  "type": "module",
  "main": "./dist/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./dist/server.js",
    "tsc": "tsc",
    "copy-views": "cpy \"src/**/*.mustache\" dist --parents",
    "build": "npm run tsc && npm run copy-views",
    "type-check": "tsc -p tsconfig.json --noEmit"
  },
  "keywords": [],
  "author": "Keegan Churchill",
  "license": "MIT",
  "dependencies": {
    "@types/expr-eval": "^1.0.2",
    "body-parser": "^1.20.3",
    "dotenv": "^16.4.7",
    "expr-eval": "^2.0.2",
    "express": "^4.21.2",
    "mustache-express": "^1.3.2",
    "mysql2": "^3.11.5",
    "nodemailer": "^6.9.16"
  },
  "devDependencies": {
    "@types/express": "^5.0.0",
    "@types/node": "^22.10.2",
    "cpy-cli": "^5.0.0",
    "ts-node": "^10.9.2",
    "ts-node-dev": "^2.0.0",
    "typescript": "^5.7.2"
  }
}

tsconfig.json

{
  "compilerOptions": {
     "target": "ES2020",
     "module": "ESNext",
     "rootDir": "./src", 
     "moduleResolution": "node",
     "allowJs": false, 
     "outDir": "./dist",
     "esModuleInterop": true,
     "forceConsistentCasingInFileNames": true, 
     "strict": false,   
     "skipLibCheck": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["dist", "node_modules"],
}

具体来说,我收到错误 404 代码未在 vercel 构建日志中找到,但未显示运行的构建命令。一切都在本地编译和运行。

我尝试过各种构建命令,甚至尝试回显命令以查看它是否会打印在 vercel 构建日志中。我在项目设置中没有构建命令覆盖,它们全部显示为灰色,因为 vercel 需要 vercel.json。我还尝试安装开发依赖项,以防问题是 vercel 未安装打字稿编译器。这有点令人困惑,因为没有构建错误,只有代码未找到错误。在我看来,剩下两个选择。 Vercel 未在 vercel.json 或 package.json 中运行构建命令。或者 vercel 正在构建东西但找不到 dist/server.js。另一件需要注意的事情是,预打字稿 Express 应用程序托管在 vercel 上,没有任何问题,可以正确路由到主页。谢谢所有 vercel 专家爱好者,节日快乐!

typescript express deployment vercel
1个回答
0
投票

这是解决我的问题的 vercel.json。主要将 vercel 构建指向 server.ts,而不是 server.js。

{
  "version": 2,
  "builds": [
    {
      "src": "src/server.ts",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "src/server.ts"
    },
    {
      "src": "/(.*)",
      "dest": "dist/server.js"
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.