TypeScrpt Error: Cannot find name 'require'. (2304)
Created by: huan
The Problem
$ cat test-require.ts
const fs = require('fs')
fs.statSync('/')
console.log('OK')
$ ts-node test-require.ts
TSError: ⨯ Unable to compile TypeScript
require.ts (1,12): Cannot find name 'require'. (2304)
You got the Cannot find name 'require'. (2304)
Error.
However, the same code with a .js
extension run by node
without any problem:
$ cp test-require.ts test-require.js
$ node test-require.js
OK
I believe this problem is the most stupid design for TypeScript because it heavy increased the studying curve and lied on their slogan "TypeScript is the superset of JavaScript": a good JavaScript code will fail under TypeScript.
The Solution
- We need to use
import
instead of const/var withrequire
- const fs = require('fs')
+ import fs = require('fs')
However, after this modification, we re-run ts-node test-require.ts
will get a new TS2351 Error:
Cannot find module 'fs'. (2307)
- In order to fix this new problem, we have to make another extra step:
$ npm install @types/node
After installed @types/node, re-run ts-node require.ts
will be ok:
$ ts-node require.ts
OK
A TypeScript issue discussion at here