Deb
Deb

Reputation: 379

Angular 6 :: Cannot find name 'require'

My project is created using angular cli [ version - 6.1.3 ]. I installed npm module - is-reachable and used it in my code as -

const isReachable = require('is-reachable');

appDetailsFromJson.forEach(app => {
        isReachable(app.server).then(reachable => {
          console.log('Hey --> ',reachable);
            //=> true
      });

However, on running the project it throws the exception - error TS2304: Cannot find name 'require'.

What is the root cause for this & what is the correct way to import a library in angular 6 ?

Upvotes: 3

Views: 6986

Answers (1)

Mark Hughes
Mark Hughes

Reputation: 7374

From the NPM page of isReachable it says (my emphasis):

Works in Node.js and the browser (with browserify).

This means that it is unlikely to work natively in an Angular application as the Angular CLI uses webpack and the standard typescript compiler (rather than browserify) to resolve imports and package dependencies.

In general, imports in Angular are standard ES6-style 'import' statements, e.g.:

import { isReachable } from 'is-reachable';

... or ...

import * as isReachable from 'is-reachable';

If is-reachable itself does not use any further require() statements, this may work, but if it uses require within its own code to bring in its dependencies, you would be in for a lot of difficulty in getting it to work at all - and it would almost certainly be better to find a different way to meet your requirement.

Upvotes: 4

Related Questions