简体   繁体   中英

How do I use CSS Houdini in Next.js

I would like to use CSS Houdini in a Next.js project I am building. I have installed, via yarn , both the CSS Houdini package I want to use along with css-paint-polyfill . I am following the webpack instructions here https://houdini.how/usage

Here is my component:

import 'css-paint-polyfill';
import workletURL from 'url-loader!css-houdini-lines';
import styles from './Separator.module.css';

CSS.paintWorklet.addModule(workletURL);

export default function Separator() {
  return <div className={styles.separator} />;
}

I am getting the dreaded

error - ReferenceError: window is not defined
at /home/tithos/code/web/new-tim/node_modules/css-paint-polyfill/dist/css-paint-polyfill.js:1:239

I tried putting the import for css-paint-polyfill in a useEffect, but the throw another error. I even tried const DynamicComponent = dynamic(() => import('../components/hello')) from https://nextjs.org/docs/advanced-features/dynamic-import , but I did not know how to reference the library.

Has any one solved this?

Seems like CSS Paint Polyfill eagerly accesses window , which means it will throw an error when in an environment which has no window , such as server phase of Next. There are multiple things you can do.

  1. Modify your next.config.js to stub the aforementioned module when for Webpack when isServer is true . You can follow this page of the Next docs for this.
  2. Create a dynamic component that's only imported on the client (I see you've tried this, but it should have worked, so maybe if you shared what you did in this regard, I could work out what's wrong with your approach).
  3. Create an issue and send in a PR to the repository where the Polyfill is hosted to lazily access window depending on whether it's available or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM