Skip to content

TypeScrpt Error: Cannot find name 'require'. (2304) #85

@huan

Description

@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

  1. We need to use import instead of const/var with require
- 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)

  1. 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions