Home > Software design >  Using styles from scss or css into Gatsby doesn't work
Using styles from scss or css into Gatsby doesn't work

Time:10-13

I'm trying to learn Gatsby and I'm stuck on using styles from SCSS after I import it on the Homepage.

Here is my Homepage (index.js) that is loading and using SCSS with React JSX.

import * as React from "react"
import styles from '../styles/home.module.scss'

const IndexPage = () => {
  return (
    <main className={styles.container}>
      <h1 className={styles.title}>Helloworld</h1>
    </main>
  )
}

export default IndexPage

Those are the styles I'm currently trying to import.

.container{
    background: purple;
}

.title{
    font-size: 5em;
    color: white;
}

I'm using SCSS that came automatically installed from Gatbsy, and here is the Config file of Gatsby.

module.exports = {
  siteMetadata: {
    siteUrl: "https://www.yourdomain.tld",
    title: "gatsby-learning",
  },
  plugins: ["gatsby-plugin-sass"],
};

So this is the weird error I get when the App runs. Gatbsy Error

CodePudding user response:

In Gatsby v3 you need to import the styles as ES modules, like this:

import * as styles from '../styles/home.module.scss'

Then, you'll be able to use your CSS modules at, for example:

<main className={styles.container}>

Keep in mind that this is not the recommended way of importing CSS modules because you are not allowing webpack to treeshake your styles. Ideally, you should import each named module like:

import { container } from '../styles/home.module.scss'

And applied as:

<main className={container}>
  • Related