Working with CodeceptJS and TypeScript offers several benefits, but it can also come with a headache issue, which is the TS2451: Cannot redeclare block-scoped variable 'I'
error.
If you encounter this issue, there are a few ways to overcome it. One approach is to add export {}
at the beginning of your test file, but this would require adding it to multiple files as your project expands.
A more elegant solution is to edit your tsconfig.json
. One option that immediately solves the problem and eliminates the need to manipulate multiple files is to add "moduleDetection": "force"
to the "compilerOptions"
section, as shown in the example below:
{
"ts-node": {
"files": true
},
"compilerOptions": {
"target": "es2018",
"lib": ["es2018", "DOM"],
"esModuleInterop": true,
"module": "commonjs",
"strictNullChecks": false,
"types": ["codeceptjs", "node"],
"declaration": true,
"skipLibCheck": true,
"moduleDetection": "force" // <<<<< adding this
},
"exclude": ["node_modules"]
}
Note that for TypeScript 4.7+, this option is documented under: https://www.typescriptlang.org/tsconfig#moduleDetection