1

Working on an existing typescript project. VS Code.

Create a new file in the server directory and get unique errors just on that file

this:

let path = require('path')

gives me the ole:

Cannot redeclare block-scoped variable 'path'.

whereas this is OK:

import * as path from "path"

Funnily enough, this

let fs = require('fs')

on its own also gives the same error, but if I include the import * as path from "path" above then that error goes away without touching it! Internal node modules are treated differently!

In many other files in the same project the

let fs = require('fs')

Gives no error at all

What is going on typescript?

I had a similar problem 2.5 years ago, and seems TS is still the same mystery box of configuration BS, now made even more opaque by VSC.

cannot redeclare block scoped variable (typescript)

this file is OK!

enter image description here

but in another file exact same code has the little squigglies!

enter image description here

but this magical combination is OK:

enter image description here

dcsan
  • 11,333
  • 15
  • 77
  • 118
  • I can't say it much better than this answer: https://stackoverflow.com/a/41975448 . (Not voting a duplicate because the question isn't exactly the same.) – Matt McCutchen Aug 06 '18 at 16:39

1 Answers1

0

Don't use require, instead use import.

The reason is, require is specific to node, where else import statement is transformed into either require or define based on target.

So when importing a module through import, TS compiler knows what and how to import. When you are importing through require method, everything is globally included in typescript. And thus the error.

Akash Kava
  • 39,066
  • 20
  • 121
  • 167