Member-only story
Typescript: builds fine locally, but fails in Heroku
I’m writing the post I wish I found when I googled the title you are currently seeing.
The context:
- a Typescript express.js app that builds (`tsc`) fine locally but fails when deployed via Heroku
- the errors were complaining about missing modules (that are dev dependencies)
The cause: How Heroku prunes dependencies. What you should know is that by the time that “start” is run, devDependencies are pruned. That meant, my scripts that looked like this:
"scripts": {
"build": "tsc",
"start": "npm run build && node ./dist/index.js",
"dev": "nodemon index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
}
Would result in errors complaining about type packages that could not be found, such as @types/express
. This is because when Typescript compiles, it would need access to the packages such as @types/express
, which in this situation it doesn’t, because Heroku already pruned all the devDependencies.
The fix:
"scripts": {
"build": "tsc",
"heroku-postbuild": "npm run build",
"start": "node ./dist/index.js",
"dev": "nodemon index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
}
The command for heroku-postbuild
will be run by Heroku right after installing all dependencies (i.e. running npm install
) but before the pruning of devDependencies.
Hope that helped!