【问题标题】:required keyword not working with angular必需的关键字不适用于角度
【发布时间】:2019-09-18 07:30:26
【问题描述】:

require 关键字不适用于 angular,抛出错误:

src/app/app.component.ts(8,16): error TS2591: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

我该如何解决?其实我也用nodejs正确安装了它,但没有工作。

【问题讨论】:

  • 查看我的回答会对你有帮助
  • 它不工作
  • 重启你的 Angular cli 服务器并关闭 vs 代码并再次打开
  • 完成了,没有任何反应

标签: javascript node.js angular typescript single-page-application


【解决方案1】:

如果您想在代码中使用 require,请按照以下步骤操作

首先安装这个包

npm i -D @types/node

然后在你的 tsconfig.json 中

"typeRoots": [
            "node_modules/@types", //add this
        ],

【讨论】:

    【解决方案2】:
    1. 正如其他人所说,您需要require吗?使用 ES6 导入。
    2. 但是,如果您确实需要require,您可以在它前面加上declare const require: any。为我工作。

    【讨论】:

    • 为什么需要使用declare const require: any?因为打字稿已经包含types/node
    • 坦率地说,我不知道。 TS 配置 应该 工作,但显然我错过了一些东西。 declare 行看起来很老套,我承认这一点,但为我解决了问题。
    • 不。想象一下你有很多文件并且需要使用require。那不是幸福的情况
    • 我不是在争论这个。但是我在整个项目中有一个require 声明。正如我所说,它适用于
    • 是的,我知道 :D 只是说我们应该做一些让我们的生活更轻松的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2019-07-21
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多