0
votes

Background

Hi!

I develop a components library and I have to build it to import in another project. So, I configurated webpack and tried to import a random component and got SSR error:

Server Error ReferenceError: document is not defined

Call Stack

insertStyleElement

node_modules/lib/dist/index.js (367:14)

Of course code (after build) below raises error in nextjs app. Its internal style-loader function.

function insertStyleElement(options) {
  var style = document.createElement('style');
  ...
}

Configs

All configs are here

Stacks

Lib stack:

  • React
  • TypeScript
  • css-modules + postcss

Main App stack:

  • TypeScript
  • Nextjs

Question

I suppose that trouble comes from style-loader (insertStyleElement is exporting from there). Where did I make mistake?

1

1 Answers

0
votes

Problem is not about webpack loaders. You try to call document.createElement but there is no document/window space on the server (you are able to work with it only in the browser).

You need to add helper inside your library:

export const isClient = () => typeof window !== 'undefined';

And then you can use it like:

var style = isClient() && document.createElement('style');