【问题标题】:Deploy a Node.js server made with TypeScript on Heroku在 Heroku 上部署使用 TypeScript 制作的 Node.js 服务器
【发布时间】:2020-07-31 21:24:03
【问题描述】:

我想在 Heroku 上部署一个使用 TypeScript 制作的 Node.js 服务器。但这不起作用。我已经阅读了很多关于 Stack Overflow 的教程和其他问题,但没有一个有效。下面我发布我的 tsconfig.json 和 package.json 代码。

package.json


  "main": "build/index.js",
  "scripts": {
    "start": "node build/index.js",
    "dev": "nodemon server.js",
    "build-ts": "tsc",
    "start:dev": "nodemon --config \"./nodemon.json\"",
    "test": "echo \"Error: no test specified\" && exit 1",
    "heroku-postbuild": "npm run build-ts"
  },
  "keywords": [],
  "author": "Gabriel Meyer",
  "license": "MIT",
  "devDependencies": {
    "@types/cors": "^2.8.6",
    "@types/express": "^4.17.3",
    "@types/node": "^12.12.31",
    "nodemon": "^2.0.2",
    "prettier": "^2.0.2",
    "ts-node": "^8.8.1",
    "tslib": "^1.11.1",
    "tslint": "^6.1.0",
    "typescript": "^3.8.3"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "uuid": "^7.0.2",
    "websocket": "^1.0.31"
  }

tsconfig.json


{
  "compilerOptions": {
    "module": "commonjs",
    "strict": true,
    "baseUrl": ".",
    "rootDir": "src",
    "outDir": "build",
    "sourceMap": true,
    "removeComments": true,
    "experimentalDecorators": true,
    "target": "ES6",
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "strictPropertyInitialization": false,
    "types": ["node"],
    "typeRoots": ["node_modules/@types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

index.ts


import express from 'express';
const app = express();
const port: string | number = process.env.PORT || 5000;
app.use('*', (req, res) => {
  res.send('<h1>Welcome to your server!</h1>');
});

// create a server object:
app.listen(port, () => console.log(`hosting @${port}`));

【问题讨论】:

  • 你有heroku的日志吗?如果你安装了 cli,你可以使用命令heroku logs --tail 来获取日志。

标签: node.js typescript heroku


【解决方案1】:

现在我找到了答案:

我的错误是,我将所有与 Typescript 相关的依赖项都放入了 devDependencies。 Heroku 需要 typescriptts-nodetslib 作为常规依赖项,以将 .ts 文件转换为 .js 文件。见下文:

package.json

"dependencies": {
    "ts-node": "^8.8.1",
    "tslib": "^1.11.1",
    "typescript": "^3.8.3",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "uuid": "^7.0.2",
    "websocket": "^1.0.31"
} 

【讨论】:

  • 这不是一个错误。更好的方法是在您的 heroku 构建过程中引入一些额外的步骤,如下所示:1)安装所有包(包括 devdeps)2)tsc 3)npm prune --production(删除开发依赖项)。有 heroku buildbacks 可以做到这一点,或者根据你的项目,你可以自己做。
猜你喜欢
  • 2016-08-30
  • 1970-01-01
  • 2022-01-09
  • 2021-09-04
  • 2018-06-13
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
相关资源
最近更新 更多