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.

2
  • I tried 'npm install @types/node' as recommended elsewhere but that didn't help Commented Sep 7, 2017 at 2: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'); Commented Sep 7, 2017 at 2:51

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.