'tsc not found in typescript express and react app when deploying to heroku

I am working on an express app(in typescript) and a react app bootstrapped with create-react-app(in js). The directory structure is here. The server directory contains code for server which is inside server/src and is written in typescript(output into server/dist on building). Similarly the code for react is inside /src and on building generates the /build directory.

The problem is when deploying to heroku, the command tsc is not working and thus build fails The stack trace is -


2020-11-29T10:11:12.328622+00:00 app[web.1]: > cd server && yarn start
2020-11-29T10:11:12.781818+00:00 app[web.1]: yarn run v1.22.10
2020-11-29T10:11:12.832721+00:00 app[web.1]: $ tsc & node .
2020-11-29T10:11:12.850144+00:00 app[web.1]: /bin/sh: 1: tsc: not found
2020-11-29T10:11:12.905249+00:00 app[web.1]: internal/modules/cjs/loader.js:303
2020-11-29T10:11:12.905252+00:00 app[web.1]: throw err;
2020-11-29T10:11:12.905253+00:00 app[web.1]: ^
2020-11-29T10:11:12.905253+00:00 app[web.1]: 

How should i include it in the package.json(s) so that this command is recognised in the heroku deployment environment.

Package.json scripts for React app is

"scripts": {
    "startClient": "react-scripts start",
    "buildClient": "react-scripts build",
    "build": "react-scripts build && (cd server && yarn install)",
    "start":"cd server && yarn start",
    "devServer":"cd server && yarn dev",
    "tsc": "tsc",  // 1)
    "postinstall": "yarn tsc" // 2)
  },

1 & 2 were added following the suggestion in How do I compile Typescript at Heroku postinstall? .

The package.json script for server app is

"scripts": {
    "build":"tsc",
    "start":"tsc & node .",   // this is the command which fails
    "dev":"tsc -w & nodemon ."
  },

i know i have to configure that postinstall so that tsc is recognised but i am not able to understand in which of the package.json's scripts i should add it to? Would appreciate if you could clarify on which one to add it to and why is that so that tsc isn't recognised. Alternatively, can i directly use npx tsc or is that not recommended ?



Solution 1:[1]

I ran into a similar issue and am not certain its the same as what you encountered but posting anyways in case its helpful to someone else.

I'm using the heroku/nodejs build pack and it looks like it runs tasks in the following order:

  • Creating runtime environment
  • ...
  • Installing dependencies
  • Build
  • Pruning devDependencies
  • ...

After the build completes successfully, the container is started with the command npm 'start' which in your case calls the tsc command which no longer exists if you installed it as a dev dependency (since it was pruned).

My solution was to move tsc out of the start step and leave it as node .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Errol Pais