问题描述
我从 Gatsby 开始,在我的应用程序中,当我运行命令时 'gatsby develop',我在终端收到这个警告:
警告尝试导入错误:“../styles/home.module.css”不包含默认导出(作为“样式”导入)。
然后,当我尝试加载页面时,这是不可能的
Unhandled Runtime Error
Cannot read property 'header' of undefined
<section className={styles.header}>
import styles from '../styles/home.module.css'
export default function Home({ data }) {
return (
<Layout>
<section className={styles.header}>
这是我的 css 模块的一部分(文件 home.module.css):
.header {
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 40px;
align-items: center;
}
我的 CSS 模块有什么问题?
解决方法
在新版本的 Gatsby (v3
) 中,需要像(作为 ES 模块)导入 CSS 模块:
import * as styles from './[componentName].module.css'
应用于您的代码:
import as * styles from '../styles/home.module.css'
请记住,这不是导入 CSS 模块的推荐方式,因为您不允许 webpack 对样式进行 treeshake。理想情况下,您应该导入所需的命名模块,例如:
import React from "react"
import { box } from './mystyles.module.css'
const Box = ({ children }) => (
<div className={box}>{children}</div>
)