Home >Web Front-end >CSS Tutorial >Why Am I Getting a 'Global CSS Cannot Be Imported' Error in My Next.js App After Installing next-images?

Why Am I Getting a 'Global CSS Cannot Be Imported' Error in My Next.js App After Installing next-images?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 01:40:17794browse

Why Am I Getting a

Next.js Global CSS ImportError After NPM Installation

Your React application may encounter an error after installing the next-images package stating, "Global CSS cannot be imported from files other than your Custom ." This issue arises after moving global CSS imports to _app.js, as instructed by the error message.

Root Cause:

Next.js version 9.2 introduced changes in how global CSS is handled. It now requires global CSS to be imported only within the Custom component.

Resolution:

To resolve this issue, follow these steps:

  1. Use the Next.js CSS Loader:

    • Replace @zeit/next-sass with sass in your package.json file.
    • Remove any modifications to CSS loading in next.config.js.
  2. Move Global CSS to _app.js:

    • Import your global CSS in the pages/_app.js file, as suggested by the error message.
  3. Import Specific CSS Modules:

    • For component-specific or page-specific styles, use CSS modules by importing them within the respective component or page file.

Example (Updated _app.js):

// pages/_app.js

import '../global-styles/main.scss'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Additional Information:

The error may have occurred even without direct changes to CSS or Layout.js because Next.js version updates may have triggered the new CSS handling requirements.

By adopting the Next.js CSS loader and importing global CSS in _app.js, you can ensure proper handling of global CSS in your Next.js application.

The above is the detailed content of Why Am I Getting a 'Global CSS Cannot Be Imported' Error in My Next.js App After Installing next-images?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn