Ask Question

NextJS: How can I lazy-load third party css?

I want to implement profile image upload for logged-in user with cropping functionality (CropperJS). CropperJS comes with its own css which needs to included in my application. But NextJS only allows to import third party css in <App> which I really don not want to since this should only get loaded for authenticated users.

Error message from NextJS:

Global CSS cannot be imported from files other than your Custom . Please move all global CSS imports to src/pages/_app.tsx

Do you guys have any solution for this issue?

NextJSReactCSS

175 views

Author´s Anki Batsukh image

Anki Batsukh

Last edited on

1 Answer available

Best answer

This is my workaround for now…
Lazy load the image cropping modal component and inject the raw css per <style> with next/head

// lazy loading
const AvatarUpload = dynamic(() => import('./avatar-upload'), {
  loading: function _Loader() {
    return <LoadingSpinner isLoading />;
  },
});

// avatar-upload.tsx
const cropperCss = `Paste the whole min.css here`

const AvatarUpload = () => {
  // ...

  return (
    <>
      <Head>
        <style>
          {cropperCss}
        </style>
      </Head>
     {/* ... */} 
    </>
  )
}
export default ProfileUserAvatarUpload;
❤️
1
👀
1
Last edited on