3

I would like to use an available npm package in my Angular 4 component but am struggling to make it work. The package is called 'ip' available from https://www.npmjs.com/package/ip

I have added the package as follows:

npm install ip --save

npm install --save @types/ip

and in my app.module.ts I have:

import { isV4Format } from 'ip';

and I add isV4Format to the imports list in app.module.ts

I then try to use the ip package it in my class as follows:

import { isV4Format } from 'ip';

export class TabValidator {
    private static _check(address: string): any {
        const ip = require('ip');
        if (!myip.isV4Format(address)) { return { 'wrongFormat': true }; }
        return null;
    }
}

The compiler complains about the component:

Cannot find name 'require'

and about app.module.ts:

Argument of type '{ declarations: (typeof InterfacesComponent | typeof EditnicComponent | typeof AppComponent)[]; i...' is not assignable to parameter of type 'NgModule'.

Can someone tell me what's wrong with the above? I suspect there are a few things wrong. I found 2 similar question on SO but they appear to be for different angular versions.

Community
  • 1
  • 1
TSG
  • 4,242
  • 9
  • 61
  • 121
  • I tried 'npm install @types/node' as recommended elsewhere but that didn't help – TSG Sep 07 '17 at 02:11
  • try to move require block right below imports like this: `import ... const ip = require('ip');` then use it in function. If it not helped, then write path to js in require block, like `const Highcharts = require('highcharts/highstock');` – Anton Lee Sep 07 '17 at 02:51

1 Answers1

1

There are lots of wrong/outdated answers on SO, including these wrong ones:

Cannot find name 'require' after upgrading to Angular4

Types not found

Angular 4: "Cannot find name 'require'

It seems that Angular has made it easier; just add this into the component where you want to use the node module:

export declare let require: any;
const ip = require('ip');

Now this may not be the BEST way to achieve what you want, since I read something about using 'require' negatively impacts code sharing or something like that in Angular. But if someone can post a better answer I'll accept that!

Community
  • 1
  • 1
TSG
  • 4,242
  • 9
  • 61
  • 121