Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby - Warn Attempted import error: 'css' does not contain a default export (imported as 'styles')

I Was beginning with Gatsby, and in my app, when I run the command 'gatsby develop', I got this warning in terminal:

warn Attempted import error: '../styles/home.module.css' does not contain a default export (imported as 'styles').

And then, when I´m trying to load a page, It´s not possible

Unhandled Runtime Error 
Cannot read property 'header' of undefined 
<section className={styles.header}>

This is part of my code (file index.js):

import styles from '../styles/home.module.css'

export default function Home({ data }) {
  return (
  <Layout>
     <section className={styles.header}>

This is part of my css module (file home.module.css):

.header {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 40px;
  align-items: center;
}

What I'm doing wrong with my CSS Module?

like image 215
Lins Avatar asked Mar 30 '21 10:03

Lins


1 Answers

From Gatsby v3 onwards, CSS modules need to be imported as ES Modules:

import * as styles from './[componentName].module.css'

Applied to your code:

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

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

import React from "react"
import { box } from './mystyles.module.css'

const Box = ({ children }) => (
  <div className={box}>{children}</div>
)

Further details: https://www.gatsbyjs.com/docs/reference/release-notes/migrating-from-v2-to-v3/#css-modules-are-imported-as-es-modules

like image 191
Ferran Buireu Avatar answered Nov 16 '22 14:11

Ferran Buireu