module not found in the file generated by typescript

229 views Asked by At

I use typescript in nodejs, when I output from the file, I cannot access the modules in the final file, and I use absolute path in the tsconfig.josn file.

// tsconfig.json
{
  "extends": "@tsconfig/node16/tsconfig.json",
  "compilerOptions": {
    "preserveConstEnums": true,
    "baseUrl": "src",
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

Here, I imported the connectDB file and there is no problem

// index.ts
import express from "express";
import dotenv from "dotenv";
import connectDB from "db";

dotenv.config();
const app = express();

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`server run on port ${PORT}`));

connectDB(app, PORT);

But when the file is generated, I get the error Cannot find module 'db'

// dist/index.js

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const dotenv_1 = __importDefault(require("dotenv"));
const db_1 = __importDefault(require("db"));
dotenv_1.default.config();
const app = (0, express_1.default)();
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`server run on port ${PORT}`));
(0, db_1.default)(app, PORT);

I want to use absolute path so that I can access the modules in the final file and not get an error

1

There are 1 answers

0
Live bug help - www.dialect.so On

TypeScript doesn't do path resolution at runtime; you have to use a library like https://www.npmjs.com/package/tsconfig-paths to resolve absolute paths at runtime.