Home >Web Front-end >CSS Tutorial >How Can I Fix the 'Global CSS cannot be imported from files other than your Custom ' Error in Next.js?

How Can I Fix the 'Global CSS cannot be imported from files other than your Custom ' Error in Next.js?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 11:29:10379browse

How Can I Fix the

Next.js Global CSS Importation Dilemma

In Next.js, managing global CSS can be tricky. Recently, a user encountered a perplexing error: "Global CSS cannot be imported from files other than your Custom ". This error signifies that CSS imports should be relocated to pages/_app.js.

Analyzing the Cause

The error typically arises when using legacy third-party packages like @zeit/next-sass for CSS loading. With the release of Next.js 9.2, global CSS imports have become mandatory within the Custom component. This change was implemented to improve performance and simplify CSS handling.

A Step-by-Step Solution

To resolve the error and manage global CSS effectively, consider the following steps:

  1. Switch to Built-in CSS Loader: Migrate from @zeit/next-sass to the built-in Next.js CSS loader by installing sass.
  2. Remove Custom CSS Configuration: Delete next.config.js or avoid modifying CSS loading configurations within it.
  3. Relocate Global CSS: Move global CSS imports to pages/_app.js, as indicated by the error message.

Example of pages/_app.js with Global CSS Import:

// pages/_app.js
import '../global-styles/main.scss'

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

Using CSS Modules for Scoped Styling

To apply styling specific to components or pages, Next.js offers built-in support for CSS modules. By creating a Sass file with the same name as the component (e.g., button.module.scss), you can define scoped styles that are only applied to that component.

In Conclusion

Next.js's latest approach to CSS management requires global styles to be imported within the Custom component. Implementing the suggested solutions will help prevent the "Global CSS cannot be imported from files other than your Custom " error and ensure effective CSS handling.

The above is the detailed content of How Can I Fix the 'Global CSS cannot be imported from files other than your Custom ' Error in Next.js?. 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