【问题标题】:Angular 4 Cannot find name ErrorAngular 4找不到名称错误
【发布时间】:2018-02-02 19:16:10
【问题描述】:

我正在使用 jwt 简单库:

https://www.npmjs.com/package/jwt-simple

在我的一个打字稿中,我有以下内容:

const jwt = require('jwt-simple');
const payload = { user: 'joesan' };
const secret = 'testtest';

现在当我运行这个应用程序时,它在它有 require(...) 的地方失败了。它失败并显示以下消息:

Cannot find name 'require'.

关于问题可能是什么的任何想法?

【问题讨论】:

    标签: angular jwt-simple


    【解决方案1】:

    请看这里 - nodejs require inside TypeScript file

    Typescript 不使用 CommonJS 的依赖项导入方法,因此您必须对其稍作调整。

    首先,您需要确保在您的 tsconfig.json 文件中将 allowJS 选项设置为 true。

    {
        "compilerOptions": {
         ... 
        "allowJS": true,
         ...
         }
    }
    

    现在我正在粘贴上面链接中的最佳相关答案

    正确的语法是:

    import sampleModule = require('modulename');或

    import * as sampleModule from 'modulename';然后编译你的 带有 --module commonjs 的 TypeScript。

    如果包没有附带 index.d.ts 文件并且它是 package.json 没有“typings”属性,tsc 会叫它 不知道“模块名”指的是什么。为此,您需要 在http://definitelytyped.org/ 上为它找到一个 .d.ts 文件,或者写一个 自己。

    如果您正在为 Node.js 编写代码,您还需要 node.d.ts 来自http://definitelytyped.org/的文件。

    如果您使用 angular CLI,您也可以尝试将其添加到 angular-cli.json 中的“脚本”参数中

      },
      "apps": [
        {
          "main": "src/main.ts",
          "styles": [
            "../node_modules/bootstrap/dist/css/bootstrap.min.css"
          ],
          "scripts": [   // HERE 
            "../node_modules/bootstrap/dist/js/bootstrap.min.js"
          ],
          "tsconfig": "src/tsconfig.json",
          "mobile": false
        }
      ],
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用import jwt-simple 代替 require 语句。

      【讨论】:

        猜你喜欢
        • 2016-01-24
        • 2017-09-14
        • 2018-03-30
        • 1970-01-01
        • 2018-07-31
        • 2018-01-03
        • 2017-09-18
        • 2019-07-12
        相关资源
        最近更新 更多