I’m not sure whether I am misunderstanding something here or it is a TypeScript / VSCode bug… why am I not always getting the error shown in example.ts
when I use artificialLatency
without importing it?
I expect to see the error regardless of whether I export it or not, since I’m never importing it, but the error disappears when I delete export
.
I am using the default react-ts
Vite template
example.ts
const myOtherVar = artificialLatency;
console.log(myOtherVar);
example2.ts
export const artificialLatency = 2000;
console.log(artificialLatency);
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
2
Answers
When a JavaScript or TypeScript file does not contain any
import
orexport
keywords, it is not a module and the variables such asartificialLatency
may end up on the global scope so the code may work (for example ifartificialLatency.ts
is compiled toartificialLatency.js
and added to a Web page via a<script>
tag).The best thing to do is to ensure all files that are supposed to be modules contain at least one
import
orexport
keyword.Historically, TypeScript used the presence of
import
andexport
statements as a heuristic for determining whether a file should be checked as a module instead of a classic script.There is a compiler option
moduleDetection
which can be configured to control this behavior: