Search code examples
angularjwt-simple

Angular 4 Cannot find name Error


I'm using the jwt simple library:

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

In one of my Typescript, I have the following:

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

Now when I run this application, it fails in the place where it has the require(...). It fails with the following message:

Cannot find name 'require'.

Any ideas as to what the problem might be?


Solution

  • See here - nodejs require inside TypeScript file

    Typescript doesn't use the CommonJS method of dependency importing, so you'll have to tweak it a little.

    First you need to make sure the allowJS option is set to true in your tsconfig.json flie.

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

    Now i'm pasting the best relevant answer from the link above

    The correct syntax is:

    import sampleModule = require('modulename'); or

    import * as sampleModule from 'modulename'; Then compile your TypeScript with --module commonjs.

    If the package doesn't come with an index.d.ts file and it's package.json doesn't have a "typings" property, tsc will bark that it doesn't know what 'modulename' refers to. For this purpose you need to find a .d.ts file for it on http://definitelytyped.org/, or write one yourself.

    If you are writing code for Node.js you will also want the node.d.ts file from http://definitelytyped.org/.

    If you're using angular CLI, you could also just try adding it to the 'scripts' parameter in the 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
        }
      ],