错误:找不到模块“ nexmo”和错误TS2307:找不到模块nexmo

时间:2020-08-19 13:05:26

标签: javascript typescript requirejs nestjs nexmo

所以我正在使用 NestJs 框架和打字稿

我被要求使用 Nexmo 的节点库添加两个要素认证(SMS)。 这是他们网站上的链接:https://dashboard.nexmo.com/getting-started/verify

在开发模式下,一切都按承诺进行。

但是当我尝试为生产而构建时,出现此错误:

Error: Cannot find module 'nexmo'

所以我开始搜索它。

我首先阅读了有关导入与要求的信息。

NestJs项目中的几乎所有内容都可以与导入一起使用。

但是我记得有时使用require没问题。 例如,当我不得不使用这两个时,我没有问题:

const axios = require('axios');
const xml2js = require('xml2js');

然后我遇到了遇到类似问题的人们,他们能够通过修改其tsconfig.json来解决这些问题。

有些人添加了“ moduleResolution”:“节点” ,而不是“ moduleResolution”:“经典” ,而其他人更改了“ module”:“ commonjs” “模块”:“ AMD” ,或“模块”:“ ESNext”

我尝试了所有这些都无济于事。有时错误是由以下原因引起的:

Error: Cannot find module 'nexmo' 

收件人:

error TS2307: Cannot find module nexmo

然后,我开始阅读此处以了解有关此问题的更多信息: https://www.typescriptlang.org/docs/handbook/module-resolution.html

再次找不到我的解决方案。

我的一个朋友告诉我检查有关安装类型的内容,但是NestJs已经使用了 @types ,据我了解,这是键入的更新版本。

除此之外,我没有运气。 我所知道的是,该项目必须从ts编译为js,并且由于某种原因,NestJs在node_modules文件夹中找不到nexmo。

您能帮我或指导我正确的方法吗?

2 个答案:

答案 0 :(得分:2)

好-从全新安装中尝试了一些方法,这就是我要做的工作:

// tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true, <- this seems to be the important one 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();
  }
}

然后我跑了

~/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

答案 1 :(得分:1)

查看Github上的Nexmo软件包,我在这里看到它正在从其主模块https://github.com/Nexmo/nexmo-node/blob/master/src/Nexmo.js#L175

中导出默认值。

这意味着您在打字稿文件中应该可以简单地说:

import Nexmo from 'nexmo';

npm中的某些软件包不是commonjs友好的(意味着它们不是node js模块友好的),在这种情况下,您需要使用以下语法将其导入到typescript中:

import Nexmo = require('nexmo');

首先给一个镜头,看看它是否对您有用。