How to import Sass modules in Next.js components

Viewed 2969

With the latest Next.js I can import Sass styles globally in pages/_app.js with a directive like import '../styles/global.scss'; and without depending on @zeit/next-sass.

Does this work at the component level? For example, can I have a components/* directory where I keep my components, and each component has a *.tsx file that imports a *.module.scss file?

That's not working for me right now. I don't get errors but component-level styles don't load while the global styles do.

Edit: To be clear, I do not want to import an object like import styles from ...scss. I simply want to import Sass for this component, not any object that has properties.

Here's a code example where I can see the globals.scss styles but not the Main.module.scss styles when I run it with npx run dev.

From scratch I ran npx create-next-app _ and then npm install sass. There are only five important files, once I make a simple Main component that I want to style:

  • components/Main/Main.tsx :
import './Main.module.scss';

export default function Main() {
  return <div className="Main">Main</div>;
};
  • components/Main/Main.module.scss :

This rule is not applied for some reason!

.Main {
    color: blue;
}
  • pages/_app.js :

These global styles do get applied!

import '../styles/globals.scss';

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
};
  • pages/index.js :
import Head from 'next/head';
import Main from '../components/Main/Main';

export default function Home() {
  return (
    <div>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Main />

    </div>
  )
};
  • styles/globals.scss :

This style rule is applied but not color: blue above.

* {
  box-sizing: border-box;
}
1 Answers

Because Sass modules scope the class names within the modules they are used, you'll need to import it as an object (styles in this example) and each class is accessed as a property on the imported object.

import styles from './Main.module.scss';

export default function Main() {
    return <div className={styles.Main}>Main</div>;
};
Related