How to configurate webpack to build react components library with css-modules for Next.js application?

881 views Asked by At

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

There are 1 answers

3
Max Arzamastsev On BEST ANSWER

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');