Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript.

My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website:

During the development phase, everything functioned smoothly as expected.

However, upon attempting to build for production, an issue arose:

Error: Cannot find module 'nexmo'

To troubleshoot, I delved into researching this dilemma.

I began by studying the distinction between import and require.

The majority of my NestJs project relies on imports, but I recalled instances where require was employed without any issues – such as when integrating axios or xml2js.

Subsequently, I encountered individuals experiencing similar obstacles, which they managed to resolve by adjusting their tsconfig.json file. Some opted for "moduleResolution": "node", while others switched from "module": "commonjs" to either "module": "AMD" or "module": "ESNext".

Despite trying all these solutions, the error persisted, fluctuating between variations.

This led me to seek further insights through reading about module resolution within TypeScript: https://www.typescriptlang.org/docs/handbook/module-resolution.html

Unfortunately, none of these resources yielded a solution.

A colleague suggested exploring the possibility of installing typings, yet NestJs already employs @types, which is considered an advanced version of typings.

At present, I remain at an impasse. My understanding thus far suggests that the conversion of the project from ts to js is imperative, but for reasons unknown, NestJs encounters difficulty locating the nexmo library within the node_modules directory.

If you possess any guidance or can direct me towards a viable solution, it would be greatly appreciated.

Answer №1

After trying different approaches with a fresh installation, I managed to get the following configurations to work:

//tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true, <- this appears to be crucial here
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}

//app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import Nexmo from 'nexmo';

const nexmo = new Nexmo({
  apiKey: '',
  apiSecret: '',
});

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    console.log(nexmo.verify);
    return this.appService.getHello();
  }
}

Subsequently, I executed

~/G/A/test-nest> master > nest build
~/G/A/test-nest >master >node ./dist/main
[Nest] 21347   - 08/19/2020, 11:36:27 AM   [NestFactory] Starting Nest application...
[Nest] 21347   - 08/19/2020, 11:36:27 AM   [InstanceLoader] AppModule dependencies initialized +18ms
[Nest] 21347   - 08/19/2020, 11:36:27 AM   [RoutesResolver] AppController {}: +7ms
[Nest] 21347   - 08/19/2020, 11:36:27 AM   [RouterExplorer] Mapped {, GET} route +3ms
[Nest] 21347   - 08/19/2020, 11:36:27 AM   [NestApplication] Nest application successfully started +3ms

Answer №2

After inspecting the Nexmo package on Github, it appears that a default value is being exported from its main module: https://github.com/Nexmo/nexmo-node/blob/master/src/Nexmo.js#L175

So in your typescript file, you should be able to simply do:

import Nexmo from 'nexmo';

However, some npm packages are not compatible with CommonJS (which means they are not node js module friendly). In such cases, you would need to import them in typescript using this syntax:

import Nexmo = require('nexmo');

Give the first method a try and see if it works for you.

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

Steps to substituting characters within a date string

Create a function called normalize that changes '-' to '/' in a given date string. For example, normalize('20-05-2017') should output '20/05/2017'. This is my attempt: let d = new Date('27-11-2021'); fun ...

Easy ways to manipulate the style of array components in Vue.js

Hey there all you programmers, I'm reaching out to see if any of you have insight on how I can modify the style of a specific component within an Object array. This is the code snippet: <template> <div> <ul> <li v-fo ...

PHP: Establishing SESSION Variables

On Page1.php, there is a variable called "flag" with the value of 1. When clicked, it triggers the JavaScript function named "ajaxreq()" which will display the text "Click me" from an AJAX request originating from page2.php. If you click on the "Click me" ...

Stopping autoplay in Swiper as soon as you hover over it

My swiper is set to autoplay, but I want it to stop immediately when hovered over instead of waiting for the transition to finish. Is there a way to interrupt the transition and stop it at the exact point where the cursor hovers? Here is my Swiper config ...

Gradual disappearance of preloader as the page loads

I'm facing an issue with setting a gif as a website preloader. Despite trying different JavaScript solutions, the preloader remains visible even after the page has finished loading. $(window).on("load", function() { $(".loading").fadeOut("slow"); ...

Mastering the proper usage of the import statement - a guide to seamless integration

I'm excited to experiment with the npm package called camera-capture, which allows me to capture videos from my webcam. As someone who is new to both npm and typescript, I'm a bit unsure about how to properly test it. Here's what I've ...

Is it possible to export a constant from within a default function to a different file?

As a newcomer to React and React Native, I am looking to pass a const variable from within a function to another file. I attempted defining it outside of the function and allowing it to be modified inside the function, but encountered an invalid Hook Call ...

Dynamic form in Yii2 developed by wbraganca that displays or hides fields depending on the value of a radio button

I am currently using the wbraganca dynamic form in a popup modal. I need to display and validate fields based on the selection of a radio button. To achieve this, I am calling a JavaScript function in the onchange event. <?= $form->field($model, "[{ ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...

Retrieving the event name from a CustomEvent instance

Looking to retrieve the name of a CustomEvent parameter in a function, which is basically the string it was created with (new CustomEvent('foo')) If you need a reference, check out https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent ...

Is it considered poor practice in TypeScript to manually set the type when the type inference is already accurate?

Is it necessary to explicitly set the variable type in TypeScript when it is inferred correctly? For example: const add = (a: number, b: number) => a + b; const result = add(2, 3); // Or should I explicitly declare the return value type? const add = ...

Re-establishing connections in the force-directed graph model

Just getting started with d3.js and I'm currently attempting to reconnect paths between nodes on a force graph. Here is an example image of what I am trying to achieve: I want to be able to drag the red circle and have the path connected to other nod ...

Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help. Here are the two interfaces I'm using: export interface Group { gId: number; gName: st ...

Mastering Inter-Composable Communication in Vue 3: A Guide

Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app. Discover More About Extracting Composables for Code Organization "Extracted composables act as component-scoped servi ...

I am continuously encountering the error message "Resource loading failed" whenever I attempt to launch a React application

I'm currently developing a React App using Webstorm as my IDE. Everything seems to be configured correctly, but whenever I attempt to run the app, I encounter an error message stating "Failed to load resource: the server responded with a status of 404 ...

Tips for importing a library in a TypeScript file that expands a JavaScript prototype

After following the instructions provided in this question, I am experimenting with integrating Moment.js to enhance the capabilities of the Date prototype within a TypeScript project. The process of extending the Date prototype appears successful, as out ...

Am I utilizing React hooks correctly in this scenario?

I'm currently exploring the example, but I have doubts about whether I can implement it in this manner. import _ from "lodash"; ... let [widget, setWidgetList] = useState([]); onRemoveItem(i) { console.log("removing", i); ...

Error: Headers cannot be set once they have already been sent

My app.js file has the following code snippet: app.use(function(req, res, next){ if(!req.user){ return res.redirect('/login_'); } next(); }) Everything seems correct so far. In my route/index.js file, I have the following code: rout ...

Simplify your code with promises in JavaScript

Running on an API with node v6.3.0, I have the following code that executes two separate promises based on a conditional check for a parameter in a POST request. if (paramExists) { // query database with this condition User.filter(/* utilize param ...

Refreshing Rails Views by Periodically Polling the Database

We are currently developing a statusboard to monitor all our external servers. Our database contains information about OS, software versions, and other details that are subject to frequent updates. To ensure real-time visibility of these changes on the web ...