代码之家  ›  专栏  ›  技术社区  ›  Soon Winner

TypeError:superheroes.random在使用“超级英雄”npm包时不是函数[关闭]

  •  -2
  • Soon Winner  · 技术社区  · 6 月前

    我正在尝试使用 superheroes 我的Node.js项目中的npm包生成了一个随机的超级英雄名字,但我一直遇到一个错误:

    TypeError: superheroes.random is not a function
    

    这是我的代码:

    import superheroes from "superheroes";
    
    const name = superheroes.random();
    
    console.log(`I am ${name}!`);
    
    

    当我运行它时,我也会收到以下警告:

    (MODULE_TYPELESS_PACKAGE_JSON) Warning: Module type of file is not specified and it doesn't parse as CommonJS. Reparsing as ES module because module syntax was detected.
    To eliminate this warning, add "type": "module" to package.json.
    

    我尝试过的步骤:

    1. 补充 "type": "module" 在里面 package.json 以解决模块类型警告。

    2. 已重新安装 超级英雄 包装使用:

      npm uninstall superheroes
      npm install superheroes
      
    3. 已检查Node.js版本( node -v )并确保它是最新的。

    观察:

    • 当我记录 超级英雄 对象( console.log(superheroes); ),它似乎没有 random() 功能。

    • 这个 superheroes.all 属性运行良好(它包含一系列超级英雄的名字)。

    为什么是 superheroes.random 没有按预期工作?软件包中是否存在错误,还是我使用不当?如何使用此包生成随机的超级英雄名称?

    1 回复  |  直到 6 月前
        1
  •  0
  •   Mureinik    6 月前

    回到3.0.0版本,你曾经有一个 random() 方法。它在4.0.0中进行了更改,现在称为 randomSuperhero() .

    要么将安装降级为3.0.0,要么更好的是,更改代码以使用现代 randomSuperhero() .