The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application.

If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details:

index.ts

import logger  from './logger';
logger.info(`🚀🚀🚀 logger is up !!`);

logger.ts

import winston from 'winston';
import CloudWatchTransport from 'winston-aws-cloudwatch';

const logger = winston.createLogger();
logger.add(new CloudWatchTransport({logGroupName:'my-api', logStreamName: 'lstream'}));
logger.level = 'silly';

export default logger;

tsconfig.json

{
    "compilerOptions": {
    "target": "es2017" ,
    "module": "commonjs" ,
    "lib": [
        "es2017",
        "esnext.asynciterable"
    ] ,
    "allowJs": true ,
    "sourceMap": true ,
    "outDir": "./dist" ,    
    "noUnusedLocals": true ,
    "noUnusedParameters": true ,
    "noImplicitReturns": true ,
    "noFallthroughCasesInSwitch": true ,
    "moduleResolution": "node" ,
    "baseUrl": "./" ,
    "paths": {
        "*": ["node_modules/*", "src/types/*"]
    } ,
    "allowSyntheticDefaultImports": true ,
    "esModuleInterop": true 
    }
}

package.json

{
  "name": "winston-aws",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "ts-node index.js",
    "watch-node": "nodemon dist/index.js",
    "watch": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"yellow.bold,cyan.bold\" \"npm run watch-ts\" \"npm run watch-node\"",
    "watch-test": "npm run test -- --watchAll",
    "build-ts": "tsc",
    "watch-ts": "tsc --traceResolution -w"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "winston": "^3.0.0",
    "winston-aws-cloudwatch": "^2.0.0"
  },
  "devDependencies": {
    "@types/node": "^10.3.3",
    "babel-preset-env": "^1.7.0",
    "concurrently": "^3.5.1",
    "nodemon": "^1.17.5",
    "ts-node": "^6.1.1",
    "typescript": "^2.9.2"
  }
}

When attempting to run the application using npm run watch, I encounter the following error:

[Node] internal/modules/cjs/loader.js:596
[Node]     throw err;
[Node]     ^
[Node]
[Node] Error: Cannot find module './lib/'
[Node]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
[Node]     at Function.Module._load (internal/modules/cjs/loader.js:520:25)
[Node]     at Module.require (internal/modules/cjs/loader.js:650:17)
[Node]     at require (internal/modules/cjs/helpers.js:20:18)
[Node]     at Object.<anonymous> (/Users/nishant/dev/sscce/dist/node_modules/winston-aws-cloudwatch/index.js:1:80)
[Node]     at Module._compile (internal/modules/cjs/loader.js:702:30)
[Node]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
[Node]     at Module.load (internal/modules/cjs/loader.js:612:32)
[Node]     at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
[Node]     at Function.Module._load (internal/modules/cjs/loader.js:543:3)

It appears that TypeScript successfully resolved the path:

[TypeScript] ======== Module name './lib/' was successfully resolved to '/Users/nishant/dev/sscce/node_modules/winston-aws-cloudwatch/lib/index.js'. ========

However, I noticed that while

node_modules/winston-aws-cloudwatch
contains a lib directory, it is missing in
dist/node_modules/winston-aws-cloudwatch
.

At this stage, I'm uncertain about what could be causing the issue.

Answer â„–1

Ah, finally after much experimentation and troubleshooting, I discovered the root cause:

 "allowJs": true ,

It seems that a key culprit was mistakenly copying certain sections of node_modules to ./dist, with one problematic file being highlighted in the error message:

dist/node_modules/winston-aws-cloudwatch/index.js

The issue boiled down to two primary factors:

  1. I initially believed that all contents within node_modules should be transferred to dist. However, this assumption was incorrect.

    Instead, nothing from node_modules should be included in dist; the compiled files should reference the correct paths to locate node_modules.

  2. The second dilemma arose when I could not resolve the error by toggling various tsconfig settings and rebuilding the project. This persistence of errors was due to the fact that dist DID NOT CLEAR PROPERLY.

    This revelation only came about through sheer luck after multiple attempts!

Despite the challenges faced, this experience has been enlightening. Hopefully, this insight may prove beneficial to someone else in the future.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS - activating $watch/$observe event handlers

I am looking for a way to trigger all $watch/$observe listeners, even if the watched/observed value has not changed. This would allow me to implement a "testing only" feature that refreshes the current page/view without requiring user interaction. I have a ...

Mongoose: No documents are being returned by the .find() method

UPDATE : Similar question posted here: Trouble with Mongoose find() method I'm still new to working with nodejs and nosql databases. Today, I am building an API that retrieves data from my user collection which currently has two entries : The issue ...

The reference to the Material UI component is not functioning

I am currently working on a chat application and have implemented Material UI TextField for user message input. However, I am facing an issue with referencing it. After researching, I found out that Material UI does not support refs. Despite this limitatio ...

Issue with AjaxComplete function failing to work

Currently, I am tackling the Opera workaround for printing IFrames. As we are aware, the only method to print an IFrame is by opening it in a new window and then printing it. However, I am encountering an issue where a series of ajax calls are triggered wh ...

Output JSON data using Javascript

Here is some JSON data I am working with: { "lang": [ { "SECTION_NAME": { "english": "My title" }, "SECTION_NAME_2": { "english": "My title" } } ] } I ...

Using Nextjs Image as the Background for Layout

I have a question regarding implementing a common background image for all pages in my app. Currently, I have the main page.js code that displays an image as the background using Next Image component. However, I would like this background to be present thr ...

Encountering an issue in a Next.js application while building it, where an error is triggered because the property 'protocol' of 'window.location' cannot be destructured due to being undefined

While building my nextjs application, I encountered the following error. My setup uses typescript for building purposes, although I am only using JavaScript. Build error occurred: TypeError: Cannot destructure property 'protocol' of 'window ...

Arranging an array of objects by a specific property in an Angular controller with the help of $filter

In my data set, there is an array of objects referred to as $scope.segments, which looks like this: [ { "_id": "55d1167655745c8d3679cdb5", "job_id": "55d0a6feab0332116d74b253", "status": "available", "sequence": 1, "body_original": " ...

What is the best way to retrieve nested reference data all at once from a Firestore document?

I have two distinct collections stored within my Firestore database. The first collection is users, and it can be visualized as shown here: https://i.stack.imgur.com/AKlyM.png The second collection is posts, represented by the following structure: http ...

Looking to showcase initial API data upon page load without requiring any user input?

Introduction Currently, I am retrieving data from the openweatherAPI, which is being displayed in both the console and on the page. Issue My problem lies in not being able to showcase the default data on the frontend immediately upon the page's fir ...

I'm curious about the purpose of the "^=" operator in this algorithm for finding the unpaired numbers. What exactly does it do?

I came across a fascinating code snippet that helps find a unique number in a list of duplicate numbers (where each number appears twice, except for one). function findNonPaired(listOfNumbers) { let nonPairedNumber = 0 listOfNumbers.forEach((n) => ...

What are the best practices for integrating Qt with React in TSX?

While I've figured out how to communicate qt with JS successfully, the challenge arises when trying to use React in TSX for frontend development. The previous solution failed on this front. Backend code: #./main.py import os from PySide6.QtWidgets ...

What is the best way to automatically have the first bar in a column highchart be selected when the page loads?

My highchart consists of a simple column. When I click on any bar in the chart, it gets selected. However, I also want the 1st bar to be selected by default. var chart = $('#container').highcharts(); Upon page load, I have obtained this object. ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

Incorporating Common Types for Multiple Uses

Is there a way to efficiently store and reuse typings for multiple React components that share the same props? Consider the following: before: import * as React from 'react'; interface AnotherButtonProps { disabled?: boolean; onClick: (ev ...

Encountering an Error in Laravel 8: Form Submission Issue - Uncaught TypeError Preventing Property Read

<a href="{{ url('/home') }}">Home</a> <a href="{{ route('logout') }}" onclick="event.preventDefault();document.getElementById('logout-form').submit();">Logout</a> <form ...

The Ajax response fails to update my viewmodel

I have a value and a list that I need to update from within an Ajax callback. After retrieving a fresh value using .get(), I try to assign it to my view model's property, but the UI does not refresh properly. Below is the code snippet: function Searc ...

Troubleshooting the Timepicker import issue in ant design version 5.0.3

After updating ant design to version 5.0.3, I encountered the Uncaught Error: Cannot find module 'antd/lib/time-picker/style' at webpackMissingModule issue. Any suggestions on how to resolve this? I am seeking a solution for the error coming fro ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

UI-Router causing issues with AngularJS anchorScroll functionality

Currently, I am utilizing ui-router and attempting to implement automatic scrolling within the controller. However, it seems that anchorScroll function is not working as expected. My assumption is that it may be due to having two '#' symbols in t ...