yuusf
yuusf•9mo ago

External package code throws error: window is undefined

Hello, I have imported an npm package to my project. And in this package's code, there is a condition:
if (typeof window === 'undefined') {
throw new Error('Error initializing the sdk: window is undefined');
}
if (typeof window === 'undefined') {
throw new Error('Error initializing the sdk: window is undefined');
}
Program throws "window is undefined" error at this condition above. I am able to access window object in my Deno project. Also, when I add a breakpoint to condition line in the cache folder files, I can access to window object from debug console as well. It would be great if someone help me resolve this problem. Thanks in advance.
4 Replies
Deno AI Helper
Deno AI Helper•9mo ago
Hello! 🦕 It seems like the npm package you're using is trying to access the window object, which is a global object typically available in browser environments. In Deno, the window object is not globally available like in a browser environment, but it is part of the built-in libraries provided to the TypeScript compiler. The documentation mentions that Deno has several built-in libraries that are not present in other platforms, like tsc. This is what enables Deno to properly check code written for Deno. However, in some situations, this automatic behavior can cause challenges, for example like writing code that is intended to also run in a browser. In these situations, the "lib" property of a compilerOptions can be used to modify the behavior of Deno when type checking code. If you're trying to use a package that's designed for the browser, you might need to adjust your compilerOptions to include the "deno.window" library. Here's an example of what your compilerOptions might look like:
{
"compilerOptions": {
"lib": ["deno.window"]
}
}
{
"compilerOptions": {
"lib": ["deno.window"]
}
}
This should allow Deno to recognize the window object. However, please note that this might not fully solve your problem if the npm package you're using relies on other browser-specific APIs. If you're still having trouble, could you please provide more information about the npm package you're using? That might help us understand the issue better.
yuusf
yuusf•9mo ago
I tried adding "deno.window" to "lib" in compilerOptions but it didn't work. btw, I am using Deno v1.38.0
marvinh.
marvinh.•9mo ago
npm packages get the node global object and "deno code" get's deno's global object. That's why window is not present
yuusf
yuusf•9mo ago
I see, that makes sense. Is there a way to make npm packages run in deno context? Or any other workaround would be appreciated I ended up moving the npm package files inside the deno project which resolved my issue. Thanks @marvinh. for your reply