0

In my NodeJS/Typescript project, I created a script database-init.script.ts that I run to initialize the database with sample data.

My package.json looks like this:

{
   "name": "myproject",
   ....
   "scripts": {
      ...
      "mongodb-setup": "tsc ./scripts/mongodb-setup.ts && node ./scripts/mongo-setup.js"
      
}

The problem is that the script imports some files that themselves utilize tsconfig paths shortcuts. For example some files have

import {AccountSchema} from '@schemas/account.schema'
...

My script fails because it doesn't recognize these. It gives me

error TS2307: Cannot find module '@schemas/account.schema' or its corresponding type declarations.

1 import {AccountSchema} from '@schemas/account.schema";

How can I get a script to recognize tsconfig-defined paths, without compiling the entire project?

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • Can you provide more information about your setup? How are you running this script? Are you first compiling to .js & running it, or are you using something like ts-node / deno? Are you using these custom paths in imports anywhere else in the project? If so do you see errors there? Are you able to share a minimum reproducible example on github? – g2jose Aug 03 '20 at 04:58
  • @GeorgeJose I added the relevant part of my package.json. I can put together a minimal project to demonstrate the issue if nobody has any ideas after some time. – CodyBugstein Aug 03 '20 at 05:30
  • 1
    You might find this helpful https://stackoverflow.com/questions/44676944/how-to-compile-a-specific-file-with-tsc-using-the-paths-compiler-option/44748041 - TLDR; [you cannot use the paths option in the CLI](https://www.typescriptlang.org/docs/handbook/compiler-options.html) - it's tsconfig.json only. Providing input files causes tsc to not read the `tsconfig`. You can get around it by creating a separate tsconfig just for your script that extends your base tsconfig – g2jose Aug 03 '20 at 05:44

1 Answers1

1

It seems you are looking for ts-node.

{
  "name": "myproject",
  ....
  "devDependencies": {
    ...
    "ts-node": "*"
  },
  "scripts": {
    ...
    "mongodb-setup": "node -r ts-node/register ./scripts/mongo-setup.ts"
  }
}
Daniele Ricci
  • 15,422
  • 1
  • 27
  • 55