loglevel-plugin-remote
loglevel-plugin-remote copied to clipboard
WebpackError: ReferenceError: window is not defined
When building with GatsbyJS I get this error:
"window" is not available during server side rendering.
WebpackError: ReferenceError: window is not defined
Here's what Gatsby has to say about it: https://www.gatsbyjs.org/docs/debugging-html-builds/
I'd like to import:
import log from 'loglevel';
import remote from 'loglevel-plugin-remote';
but I need to do it like this:
const log = typeof window !== 'undefined' ? require('loglevel') : null;
const remote = typeof window !== 'undefined' ? require('loglevel-plugin-remote') : null;
This has also been reported for loglevel pimterry/loglevel#146
I noticed that this is not happening for loglevel so I closed pimterry/loglevel#146, but it is happening for loglevel-plugin-remote.
One way to debug:
Install gatsby-cli globally.
gatsby new gatsby-starter-default https://github.com/gatsbyjs/gatsby-starter-default
cd gatsby-starter-default
yarn add loglevel-plugin-remote
In src/pages/index.js add import 'loglevel-plugin-remote';
gatsby build
const win = window;
if (!win) {
throw new Error('Plugin for browser usage only');
}
https://github.com/kutuluk/loglevel-plugin-remote/blob/master/src/remote.js#L1-L5
Error in error code. But the result is correct - throw an exception in a non-browser environment.
You should not connect the plugin during ssr or connect another plugin that will write logs directly to a file on the server.
const remote = typeof window !== 'undefined' ? require('loglevel-plugin-remote') : null;
Thanks for raising this issue, the above code snippet provided by you helped me hack around the error in my Next.js app.