0

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?

NooNoo
  • 83
  • 1
  • 1
  • 4

1 Answers1

0

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');
Max Arzamastsev
  • 515
  • 1
  • 5
  • 7
  • Thank you for the answer. I know about isClient helper but I dont use the document object in code. insertStyleElement is the loader internal function so I cant use something like isClient helper. – NooNoo Oct 12 '20 at 15:43
  • Oh, sorry. https://stackoverflow.com/questions/53951861/window-is-not-defined-error-when-using-style-loader-with-webpack Suppose it can help. – Max Arzamastsev Oct 12 '20 at 16:07
  • Thx. I fixed my issues with extracting css with MiniCssExtractPlugin. i will try another methods but MiniCssExtractPlugin did the trick. – NooNoo Oct 13 '20 at 10:05