Search code examples
node.jstypescriptnestjs

How to run script that uses NestJs service


I'm trying to run a script outside the src folder that uses a nest stand-alone application. I was able to fix most of the import errors by adding this to the tsconfig.json:

"ts-node": {
    "require": ["tsconfig-paths/register"]
  }

But I'm still getting this error:

/Users/xxx/Documents/GitHub/project-api/node_modules/ts-node/src/index.ts:859
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/auth/constants.ts:17:71 - error TS2552: Cannot find name 'UTCString'. Did you mean 'String'?

17 export const SIGN_MESSAGE_TEMPLATE = (address: string, utcTimeString: UTCString) =>
                                                                         ~~~~~~~~~

  /Users/xxx/Documents/GitHub/project-api/node_modules/typescript/lib/lib.es5.d.ts:544:13
    544 declare var String: StringConstructor;
                    ~~~~~~
    'String' is declared here.

    at createTSError (/Users/xxx/Documents/GitHub/project-api/node_modules/ts-node/src/index.ts:859:12)
    at reportTSError (/Users/xxx/Documents/GitHub/project-api/node_modules/ts-node/src/index.ts:863:19)
    at getOutput (/Users/xxx/Documents/GitHub/project-api/node_modules/ts-node/src/index.ts:1077:36)
    at Object.compile (/Users/xxx/Documents/GitHub/project-api/node_modules/ts-node/src/index.ts:1433:41)
    at Module.m._compile (/Users/xxx/Documents/GitHub/project-api/node_modules/ts-node/src/index.ts:1617:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/xxx/Documents/GitHub/project-api/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Function.Module._load (node:internal/modules/cjs/loader:958:12)
    at Module.require (node:internal/modules/cjs/loader:1141:19) {
  diagnosticCodes: [ 2552 ]
}

My script has this format:

import { TransactionsService } from '../../../src/transactions/transactions.service';
import { AppModule } from '../../../src/app.module';    

const prisma = new PrismaClient();
    
  async function main() {
     const app = await NestFactory.createApplicationContext(AppModule);
      const transactionService = app.get(TransactionsService);
    
     //...
    
     await app.close();
    }
    
    main()
      .catch(async (e) => {
        console.error(e);
        process.exit(1);
      })
      .finally(async () => {
        await prisma.$disconnect();
      });

Solution

  • I managed to solve the problem, I just needed to add the "files" to the tsconfig.json file.

    "ts-node": {
            "require": ["tsconfig-paths/register"]
            "files": true
          }