Home > Enterprise >  How to declare typescript types when executing a ts file on Heroku?
How to declare typescript types when executing a ts file on Heroku?

Time:04-20

I have a typescript file that I execute locally using ts-node:

"scripts": {
  "commands": "ts-node --files deploy-commands.ts",
},

When I run the command on the Heroku deployed app using the Heroku cli:

heroku run npm run commands

I get typescript errors:

ts-node --files deploy-commands.ts

/app/node_modules/ts-node/src/index.ts:820
return new TSError(diagnosticText, diagnosticCodes);
               ^
TSError: ⨯ Unable to compile TypeScript:
src/commands/picks.ts:3:26 - error TS7016: Could not find a declaration file for module 'luxon'. '/app/node_modules/luxon/build/node/luxon.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/luxon` if it exists or add a new declaration (.d.ts) file containing `declare module 'luxon';`

3 import { Settings } from 'luxon'
                               ~~~~~~~
at createTSError (/app/node_modules/ts-node/src/index.ts:820:12)

My package.json includes the types in devDependencies (I know Heroku strips these out)

"devDependencies": {
  "@types/luxon": "^2.3.1",
},

So I added types/index.d.ts with:

declare module 'luxon'

But still get the error.

CodePudding user response:

The immediate issue is that @types/luxon is declared as a dev dependency, but Heroku strips devDependencies after building your application slug by default. They aren't available at runtime.

You could disable dev dependency pruning or move that dependency to your dependencies, but a better option is to just not run TypeScript at runtime.

Instead, compile it to JavaScript in your build script and then run the JavaScript, e.g. using something like:

"scripts": {
  "build": "tsc",
  "commands": "node deploy-commands.js",
},
  • Related