簡體   English   中英

錯誤:找不到模塊“nexmo”和錯誤 TS2307:找不到模塊 nexmo

[英]Error: Cannot find module 'nexmo' & error TS2307: Cannot find module nexmo

所以我正在使用NestJs框架和typescript

我被要求使用Nexmo的節點庫添加雙因素身份驗證 (SMS)。 這是他們網站的鏈接: https://dashboard.nexmo.com/getting-started/verify

在開發模式下,一切都按承諾進行。

但是當我嘗試構建生產環境時,出現了這個錯誤:

Error: Cannot find module 'nexmo'

所以我開始用谷歌搜索它。

我首先閱讀了import 與 require

我的 NestJs 項目中的幾乎所有內容都可以使用導入。

但我記得有時使用 require 沒有問題。 例如,當我不得不使用這兩個時,我沒有問題:

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

然后我遇到了遇到類似問題的人,他們能夠通過稍微修改一下他們的 tsconfig.json 來解決這些問題。

一些人添加了"moduleResolution": "node"而不是"moduleResolution": "classic"而其他人將"module": "commonjs"更改為"module": "AMD""module": "ESNext"

我嘗試了所有這些都無濟於事。 有時錯誤是從:

Error: Cannot find module 'nexmo' 

到:

error TS2307: Cannot find module nexmo

然后我開始閱讀這里以了解更多關於這件事的信息: https://www.typescriptlang.org/docs/handbook/module-resolution.html

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

我的一個朋友告訴我檢查一些關於安裝typings的東西,但是 NestJs 已經使用了@types ,從我讀到的內容來看,它是一個更新版本的 typings。

除此之外,我沒有運氣。 我所了解的是,該項目必須從 ts 編譯為 js,並且由於某種原因 NestJs 無法在 node_modules 文件夾中找到 nexmo。

你能幫助或指導我正確的方法嗎?

好的 - 從全新安裝中嘗試了一些東西,這就是我要做的:

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

查看 Github 上的 Nexmo package,我在這里看到它正在從其主模塊導出默認值: https://github.com/Nexmo/nexmo-node/blob/master/src/Nexmo.js#L175

這意味着在您的 typescript 文件中,您應該能夠簡單地說:

import Nexmo from 'nexmo';

npm 中的某些包不是 commonjs 友好的(意味着它們不是 node.js 模塊友好的),在這種情況下,您需要使用以下語法將其導入 typescript 中:

import Nexmo = require('nexmo');

試一試第一個,看看它是否適合你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM