Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 892
Deb Avatar asked Feb 13 '26 08:02

Deb


1 Answers

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.

like image 102
Mark Hughes Avatar answered Feb 18 '26 06:02

Mark Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!