Nestjs:导入未定义的模块,但可以导入模块中的方法和函数

问题描述 投票:0回答:1

我正在将

Nestjs
与 WebStorm 和 TS 4.2.3^ 最新版一起使用。

我面临的问题有点奇怪。例如,某些模块(如

axios
)可以照常安装、导入和使用。但有些模块,尤其是 Nodejs Core,如 fs
path
,无法作为模块导入。 
但是他们的方法可以导入并使用得很好!

// ERROR: Module undefined on run:dev, but no error in IDE import path from 'path'; import fs from 'fs'; // Working fine import { join } from 'path'; import { readFileSync } from 'path';
我确信,他们有正确的 TS 类型,甚至是手动安装的。例如:

import axios from 'axios'; import path from 'path'; // path is undefined import { join } from 'path'; import { Injectable } from '@nestjs/common'; @Injectable() export class AppService { async test(input: string): Promise<void> { // working fine await axios.get() // Cannot read property 'join' of undefined await path.join() // await join() Works fine! } }
我只有一个由 Nest Cli 生成的 

tsconfig.json

。我通过 
npm start:dev -name
 启动我的应用程序,并且在运行代码之前 IDE 不会显示任何代码错误。

tsconfig.json 模块部分,只是为了确定:

"module": "commonjs"

,package.json 根本没有 
module
 部分。

node.js typescript webstorm nestjs ts-node
1个回答
45
投票
在这种情况下,IDE 有点误导我。差点忘了,我现在正在和TS打交道。有些模块似乎没有默认导出,所以:

    您应该像它们一样导入:
  • import * as fs from 'fs';
    
    
  • 或者,另一个选项是启用:
  • "esModuleInterop": true,
     在您的 
    tsconfig.json
    
    
© www.soinside.com 2019 - 2024. All rights reserved.