To configure the resolution of modules in the tsconfig.json file to use the ts-Node library in Typescript

Asked

Viewed 139 times

1

Hello, I am creating an API in typescript and the structure of my project is as follows::

api
| - src
    | - index.ts
    | - server.ts
| - package.json
| - tsconfig.json

Within api/src/server.ts I have a simple server using the express:

import Express from 'express';

export class Server {
  static async new(): Promise<Server> {
    return new Promise(async (resolve) => {
      const server = new Server()
      await server.listen()
      resolve(server)
    })
  }

  private _express!: Express

  constructor() {
    this._express = Express()
    this._express.get('/', (_, res) => res.send('Hello World!'));
  }

  async listen(): Promise<void> {
    return new Promise((resolve) => {
      this._express.listen(3000, () => {
        resolve(console.log('Example app listening on port 3000!'))
      })
    })
  }
}

And within api/src/index.ts I create an instance of that server and start the API:

import { Server } from '@/server';

Server
  .new()
  .catch((e) => console.error(e));

In my file api/tsconfig.json I made the settings of baseUrl and path as defined in the documentation of Typescript:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "baseUrl": "./",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    },
  },
}

And to run the application, I’m using the library ts-Node. Theoretically, there are no more settings that I should do so that it is possible to make the resolution of modules, ie in the file api/src/index.ts I should be able to find the module @/server but the project is giving me the following error:

erro de resolução

Could someone help me? Is there any configuration that should be done so that I can make the resolution of modules as is in the project?

1 answer

2


Try using this tsconfig here:

{
  "compilerOptions": {

    "target": "es6",
    "module": "commonjs",  
    "outDir": "./dist",
    "rootDir": "./src",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "skipLibCheck": true

  }

}

Note that I am asking him to compile the folder . /src and play the result in the folder . /dist (it is normal to do this to separate ts code from the compiled js. This way change your package.json script to star at dist:

 "scripts": {

    ...
    "start": "node ./dist/index.js"
    ...

 }

Try this, see if it works.

  • Kra... I’ve been hunting this for a long time... vlw!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.