The error we’re encountering happens because Next.js enforces rules about how global CSS is imported to prevent style conflicts and encourage modularity. Specifically, global CSS files (like .scss) can only be imported in the pages/_app.js file. This restriction doesn’t apply to CSS Modules (e.g., .module.scss), which are scoped to individual components.

To make .scss files act as global CSS and be imported in their respective places, we can use one of the following approaches:

1. Import Global CSS in _app.js

  1. Move all global .scss imports to pages/_app.js.
  2. Import them at the top of the _app.js file like this:
// pages/_app.js
import '../styles/global.scss'; // Example: main global file
import '../styles/otherGlobal.scss';

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

export default MyApp;

If we have multiple .scss files, combine or import them all in _app.js.

2. Use CSS Modules for Component-Level Styles

We can convert our .scss files to CSS Modules by renaming them to filename.module.scss and updating the import statements in our components. This approach ensures that styles are scoped to individual components, eliminating the need for global imports:
1. Rename .scss files:
From component.scss to component.module.scss.
Update component imports:

import styles from './component.module.scss';
const MyComponent = () => (
  
Hello, World!
);

This approach ensures styles are encapsulated and avoids conflicts.

Recommendation

If possible, we should prefer CSS Modules (Option 2) as they align with Next.js best practices for modular and maintainable styling. However, if our application heavily relies on global styles, Option 1 provides a cleaner transition while still adhering to Next.js guidelines.

Support On Demand!

ReactJS

Related Q&A