Error - Cannot find name 'require'

In the journey of programming, errors are like unwanted but important companions.  

So today I met with a new companion, a new error when I was trying to use the DateGenerator from  random-date-generator by below way: 

Code

DateGenerator=require(‘random-date-generator'); 

Error Message

error TS2591: Cannot find name 'require'. Do you need to install tsconfig. 

Error Fix Code : 

Replace the below code  

DateGenerator=require(‘random-date-generator'); 

To this 

import DateGeneration from "random-date-generator" 

I replaced the assignment statement to import statement and the error is fixed.  Typescript uses the 'import' statement while Javascript uses the 'require' or 'import' statement depending on use case.  So if you are using Typescript for your Angular project then it will be easiest to use  the 'import' statement.  There is a 'require.js' library for Typescript, but I feel the syntax can be clunky.

Hope this is helpful, Thank you. 

Reference: https://stackoverflow.com/questions/31173738/typescript-getting-error-ts2304-cannot find-name-require

 

 

Add comment