Last updated: Feb 27, 2024
Reading timeยท2 min
To solve the "Cannot find name window
or document
" error, add DOM
to the
lib
array in your tsconfig.json
file.
The DOM
definitions include both window and document. Adding the DOM
type
definitions is required for programs running in the browser.
DOM
to the lib
array in your tsconfig.json
fileOpen your tsconfig.json file and make
sure to add DOM
to your lib
array.
{ "compilerOptions": { "lib": [ "es2018", "DOM" // ๐๏ธ Add this ], }, }
Once you have added DOM
to your lib
array in tsconfig.json
the error
should be resolved.
The lib setting tells TypeScript which type definitions it should include.
If your code runs in the browser, add the DOM
string to your lib
array to be
able to use the window
and document
global variables in your TypeScript
code.
target
property in tsconfig.json
to ES6
If that doesn't work, make sure the
target property in your
tsconfig.json
file is set to something recent - ES6
is a good choice.
{ "compilerOptions": { "target": "ES6" } }
target
property changes which JS features are down-leveled and which are left intact. For example, arrow functions get converted to regular functions if your target is ES5
or lower.Modern browsers support all ES6 features, so try setting your target
to es6
or a more recent version.
If the error is not resolved, try to delete your npm_modules
and
package-lock.json, re-run
npm install
and reload your IDE.
If you are on macOS or Linux, issue the following commands in bash
or zsh
.
# for macOS and Linux rm -rf node_modules rm -f package-lock.json rm -f yarn.lock # ๐๏ธ clean npm cache npm cache clean --force # ๐๏ธ install packages npm install
If you are on Windows, issue the following commands in CMD.
# for Windows rd /s /q "node_modules" del package-lock.json del -f yarn.lock # ๐๏ธ clean npm cache npm cache clean --force # ๐๏ธ install packages npm install
Make sure to restart your IDE if the error persists. VSCode glitches often and a reboot solves things sometimes.
You can learn more about the related topics by checking out the following tutorials: