【问题标题】:cannot find name 'require' in angular 7(typescript 3.1.3)在 Angular 7 中找不到名称“require”(打字稿 3.1.3)
【发布时间】:2019-04-06 12:38:19
【问题描述】:

我的问题是为什么会显示这个错误?

src/app/p2p/p2p.component.ts(14,16) 中的错误:错误 TS2580:不能 找到名称“需要”。您需要为节点安装类型定义吗? 试试npm i @types/node

我已经安装了

 @types/node
in app/tsconfig.app.json have add 
"types": [
    "node" 
  ],
  "typeRoots": [ 
  "../node_modules/@types"
 ]  

但是有错误找不到'require'

【问题讨论】:

  • 显示你的 p2p.component.ts
  • 声明 var 要求:任何;导出类 P2pComponent 实现 OnInit { constructor() { var Peer = require(peer) var p = new Peer({initiator: location.hash === '#1', 涓流: false }) p.on('signal', function (data) { console.log('SIGNAL', JSON.stringify(data)) document.querySelector('#outgoing').textContent = JSON.stringify(data) }) document.querySelector('form').addEventListener ('submit', function (ev) { ev.preventDefault()}) p.on('connect', function () { console.log('CONNECT') p.send('whatever' + Math.random() ) }) } }

标签: angular typescript angular7 typescript3.0


【解决方案1】:

将以下设置添加到src/tsconfig.app.json

{
  "compilerOptions": {
    "types": ["node"]
  }
}

【讨论】:

    【解决方案2】:

    也检查tsconfig.json。您还需要在那里添加相同的设置。

    【讨论】:

      【解决方案3】:

      这都是因为 typeScript 不知道 require 关键字所以 添加一行使 typescript 知道 require 关键字

      一旦它被编译成 javascript,它就会更好地了解需要的单词并完成工作

      declare var require: any;
      
      const pokemon = require('src/assets/pokedex.json');
      

      【讨论】:

        【解决方案4】:

        将它添加到我的 tsconfig.json 后问题仍然存在,但另外添加以下行到 tsconfig.app.json 为我解决了它:

        {
        "compilerOptions": {
            "types": ["node"]
        }
        

        因此,请务必将其添加到两个文件 ./tsconfig.json./src/tsconfig.app.json 中,它应该可以工作。

        【讨论】:

        • 当我将它添加到tsconfig.app.json 时,我工作了!非常感谢!
        • 我发现我可以在tsconfig.app.json 中将"node" 添加到"types",而无需将其包含在tsconfig.json 和为我编译的项目中。
        • 赢家!问题是默认的 tsconfig.app.json 有一个 empty types 属性,它从 tsconfig.json 中删除了一个。我花了一段时间才解决这个问题
        • 这适用于 react 或任何 typescript 项目
        • @DaveNottage 输入帮助了我,从 tsconfig.app.json 中删除空类型并在 tsconfig.json 中添加 types=["node"] 为我解决了这个问题。
        【解决方案5】:

        像其他一些人一样,我也将节点添加到 tsconfig 中的“类型”数组中,并且由于某种原因它没有任何区别。很清楚这是一个 hack,这就是我解决它的方法:

        在 'require' 语句上方的任意位置添加此行: declare const require: any;

        这不是真正的解决方案,但我现在没有时间解决这种类型的管道问题。我稍后会回来处理它(或者可能不会,但这也可以)

        【讨论】:

          【解决方案6】:

          类型节点丢失

          安装@types/node:

          npm install --save @types/node
          

          yarn add @types/node
          

          编辑您的src/tsconfig.json 添加:

          {
              "compilerOptions": {
                  "types": ["node"]
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2018-07-23
            • 1970-01-01
            • 2017-11-09
            • 2017-09-14
            • 2018-01-25
            • 2016-09-15
            • 2019-02-25
            • 1970-01-01
            • 2020-01-10
            相关资源
            最近更新 更多