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

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

DDD
DDDOriginal
2025-01-06 01:30:38522browse

How Can I Fix

Next.js Global CSS Import Issues: A Troubleshooting Guide

What's the Issue?

Next.js users may encounter an error stating, "Global CSS cannot be imported from files other than your Custom ." This error indicates an attempt to import global CSS from a file outside the designated Custom component.

Why Did This Error Occur?

This error may arise when using legacy CSS loaders such as @zeit/next-sass after upgrading to Next.js 9.2. Alternatively, incorrect configuration in next.config.js can also trigger the issue.

Solution

To resolve this issue, follow these steps:

  1. Use the Built-in CSS Loader: Replace @zeit/next-sass with sass in your package.json and remove next.config.js or refrain from altering CSS loading within it.
  2. Move Global CSS to Custom : As per Next.js guidelines, import global CSS into the Custom component located at pages/_app.js.
  3. Use CSS Modules for Component Styles: For styles specific to a component or page, utilize CSS modules. Import the corresponding .module.scss file into the component to apply styles only to that component.

Example: Moving Global CSS to _app.js

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

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

Conclusion

By following these steps, you can resolve the "Global CSS cannot be imported from files other than your Custom " error and ensure proper CSS usage in your Next.js application.

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