【问题标题】:Gatsby - Warn Attempted import error: 'css' does not contain a default export (imported as 'styles')Gatsby - 警告尝试导入错误:“css”不包含默认导出(导入为“样式”)
【发布时间】:2021-06-26 09:20:45
【问题描述】:

我从 Gatsby 开始,在我的应用程序中,当我运行命令时 'gatsby develop',我在终端收到了这个警告:

警告尝试导入错误:“../styles/home.module.css”不包含默认导出(导入为“样式”)。

然后,当我尝试加载页面时,这是不可能的

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

这是我的代码的一部分(文件 index.js):

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 模块有什么问题?

【问题讨论】:

    标签: reactjs gatsby css-modules


    【解决方案1】:

    在新版 Gatsby(v3 及以上)中,CSS 模块需要作为 ES Modules 导入:

    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>
    )
    

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

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 2019-05-03
      • 2020-09-21
      • 2021-10-26
      • 2020-05-18
      • 2021-07-02
      • 1970-01-01
      • 2022-01-18
      • 2019-05-27
      相关资源
      最近更新 更多