node.jstypescriptabsolute-pathfastify

Absolute import is not working with fastify-autoload


I'm building fastify application with typescript and I'm having problems with using absolute import.

{
  "extends": "fastify-tsconfig",
  "compilerOptions": {
    "outDir": "dist",
    "sourceMap": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "baseUrl": "src",
    "emitDecoratorMetadata": true
  },
  "include": ["src/**/*.ts", "src"]
}

This is my tsconfig.json file.

import { User } from "entity/User";
import { FastifyPluginAsync } from "fastify";

const example: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
  fastify.get("/", async function (request, reply) {
    const users = await fastify.db.manager.find(User);
    return users;
  });
};

export default example;

And this is the part where I used abslute import.

Visual studio code doesn't display error with this but when I run the app, there occurs MODULE_NOT_FOUND error.

I guess this is because of the fastify-autoload plugin. Of course, I could use import with relative path instead but it would make code messy and hard to read, so I hope I can get around this.

If anyone have experience with this, please help me.


Solution

  • I found an alternative solution of using tsc-alias. Here's my tsconfig.json file.

    {
      "extends": "fastify-tsconfig",
      "compilerOptions": {
        "outDir": "dist",
        "sourceMap": true,
        "experimentalDecorators": true,
        "strictPropertyInitialization": false,
        "baseUrl": "src",
        "emitDecoratorMetadata": true,
        "paths": {
          "@entity/*": ["entity/*"],
          "@controllers/*": ["controllers/*"]
        }
      },
      "tsc-alias": {
        "verbose": false,
        "resolveFullPaths": true
      },
      "include": ["src/**/*.ts", "src"]
    }