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

846 views

AuthorΒ΄s AnkiCodes image

AnkiCodes

Last edited on

2 Answers

Best answer

NextJS 10 now comes with an out-of-the-box solution for this problem πŸ˜„

https://nextjs.org/blog/next-10#importing-css-from-third-party-react-components

πŸ‘
1
πŸŽ‰
1

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