如何将我的 Typescript Node.js 应用程序部署到 Heroku?

问题描述:

在本地测试时,我之前运行的是:

When testing locally I was previously running:

"build-live": "nodemon --exec ./node_modules/.bin/ts-node -r dotenv/config -- ./index.ts"

然后我想我的 Procfile 应该是这样的:

I then figured my Procfile should be something like:

web: ./node_modules/.bin/ts-node -- ./index.ts

但它说找不到模块typescript",即使它在 package.json 中.我在几个地方读到 ts-node 不是部署到 Heroku 的方式,所以我不知道该怎么做.

But it says module 'typescript' not found, even when it is in package.json. I read in a few places that ts-node is not the way to go to deploy to Heroku, so I am not sure what to do.

更新:我想我应该编译它,所以我尝试了:

UPDATE: I think I am supposed to compile it, so I tried:

web: ./node_modules/.bin/tsc --module commonjs --allowJs --outDir build/ --sourceMap --target es6 index.ts && node build/index.js

这成功了,但是在实际运行它时,我使用的一堆库得到找不到模块'...'".

This succeeds, however when actually running it, a bunch of the libs I'm using get "Cannot find module '...'".

你给 Heroku 的命令是通过编译 index.ts 和依赖项启动节点来启动 web进程"索引.js.根据时间的不同,index.js 在节点启动时可能存在也可能不存在.

The command you've given Heroku is to launch the web "process" by compiling index.ts and dependencies and starting node at index.js. Depending on how things are timed, index.js might or might not exist at the time node starts.

在启动应用程序时,您需要已经编译好源代码.例如,web 应该只是 web: node index.js 或类似的.

You need to already have your sources compiled by the time you want to start your app. For example, web should just be web: node index.js or similar.

每个构建过程都不同,因此您需要根据自己的设置弄清楚这一点.但是,假设您有一个经典的设置,您推送到 git,然后 Heroku 获取更改并使用新的 slug 更新应用程序.您可以只在本地编译,并将 index.js 和任何其他构建输出包含在存储库中,以便 Heroku 可以在 slug 中使用它.

Each build process is different, so you need to figure that out for your own setup. But, suppose you have a classical setup where you push to git and then Heroku picks up that change and updates the app with the new slug. You could just compile things locally and include index.js and any other build output in the repository, for it to be available in the slug for Heroku to use.

更好的方法是使用与 Heroku 集成的构建服务器.在那里完成构建后,将其配置为将构建结果发送到 Heroku.Travis 有这样一个简单的设置.这样你就不需要在你的存储库中包含构建输出,这被认为是一种反模式.

A better approach is to use a build server which has an integration with Heroku. After you do the build there, configure it to send the build results to Heroku. Travis has a straighforward setup like this. This way you don't need to include build outputs in your repository, which is considered an anti-pattern.

在侧节点上,尝试使用 tsconfig.json 来保留 tsc 配置.它将使您不必到处写这么长的命令行.

On a sidenode, try using a tsconfig.json to keep the tsc configuration. It will save you from having to write such long command lines all over the place.