Express + TS: Solve the problem of TypeScript error: "Cannot redeclare block scope variable"

Problem Description

Use Express + TS to develop a project, introduce the same dependency in two different files , red wavy line

Although the program can run normally



 other problems

  • Cannot redeclare block scope variable
  • Function implements repetition
  • duplicate identifier

 problem causes

The CommonJS specification is used in the project to perform import and export operations between modules

Because in the CommonJS specification, there is no "module" concept like ESModule that can form a closure. All modules are thrown to the global by default when they are referenced. Therefore, when a module is declared again, TypeScript will think that the repeated declaration twice is the same variable and throw an error.


Solution

method one

  The solution is to add a line of code export {} at the bottom of the error file



 This line of code will make it think that the current file is an ESModule module, so there is no possibility of repeated declaration of variables .

 When using this method, remember to configure your  tsconfig.json file like this: add a line of code  

"esModuleInterop": true   This configuration allows  export keywords to appear in the file.

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "rootDir": "./src",
    "outDir": "./build",
    "strict": true
  }
}

 Method Two

To initialize TS, under the path of the project, open the terminal and run the following command to initialize TS and generate  tsconfig.json 文件

tsc --init

If there is an error in the article, please ask everyone to ask questions, I would be very grateful. If you don't understand, you can comment, and I will reply one by one.

If the article is helpful to everyone, I hope you can give it a thumbs up and encourage it. There will be a long way to go to work together in the future, and the road will be long and difficult.

Guess you like

Origin blog.csdn.net/qq_52855464/article/details/130300509