current-device icon indicating copy to clipboard operation
current-device copied to clipboard

Uncaught ReferenceError: window is not defined

Open zm1994 opened this issue 6 years ago • 3 comments

I'm getting error when use this library on browser. Full error: Uncaught ReferenceError: window is not defined at Module../node_modules/current-device/es/index.js (index.js:4)

From the code of library - something is wrong with: "var previousDevice = window.device;"

My code: const device = require('current-device').default; const isMobile = function () { return device.mobile(); };

I use webpack 4 for building.

zm1994 avatar Jan 07 '19 09:01 zm1994

An option to set the window object would be nice. e.g.: device(window) or device(customWindow)

Blitzlord avatar Jan 21 '19 16:01 Blitzlord

I use ava and browser-env to test my frontend app. However this seems not to work as it fails:

var previousDevice = window.device;
                     ^

ReferenceError: window is not defined
    at Object.<anonymous> (/foo/node_modules/current-device/lib/index.js:8:22)

It looks like code is executed as soon as the import of current-device has been made

neophob avatar Mar 27 '19 21:03 neophob

In case anyone is here looking for potential solutions, I was able to import the package without the window error in Next.js like this:

// _app.js (Next.js)

// Whatever initial code here

const MyApp = ({ Component, pageProps }) => {
  // Whatever code here
  
  const currentDevice = async () => {
    await import("current-device");
  };

  useEffect(() => {
    currentDevice();
  }, []);

  // Whatever other code here

};

export default MyApp;

asheabbott avatar Mar 27 '22 16:03 asheabbott