Gatsby with PostCSS 8 - Attempted import error: 'component.module.css' does not contain a default export (imported as 'styles')

Gatsby with PostCSS 8 - Attempted import error: 'component.module.css' does not contain a default export (imported as 'styles')

我有一个基于入门项目的 Gatsby 和 Sanity 站点。到目前为止,一切都运行良好,但我今天在我的 package.json 文件中更新了我所有的软件包和插件,以消除所有 npm 警告。这包括更新到 Gatsby 3.0.3 和 PostCss 8(我现在也在使用 gatsby-plugin-postcss 4.0.0)。

我设法解决了一些初始错误,但现在我遇到了无法识别我的 CSS 模块的问题。我得到每个组件文件的错误:

尝试导入错误:“[componentName].module.css”不包含默认导出(导入为 'styles')

当我在反应组件中导入 css 文件时

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

样式对象 returns 未定义。我需要降级到其中一些软件包的旧版本吗?

这是我的 package.json:

  "dependencies": {
    "@cloudflare/wrangler": "^1.15.0",
    "@fontsource/montserrat": "^4.2.2",
    "@fontsource/raleway": "^4.2.2",
    "@sanity/block-content-to-react": "^2.0.7",
    "@sanity/client": "^2.2.6",
    "@sanity/image-url": "^0.140.22",
    "date-fns": "^2.19.0",
    "dotenv": "^8.2.0",
    "gatsby": "^3.0.3",
    "gatsby-plugin-anchor-links": "^1.2.1",
    "gatsby-plugin-manifest": "^3.0.0",
    "gatsby-plugin-react-helmet": "^4.0.0",
    "gatsby-source-sanity": "^6.0.5",
    "get-youtube-id": "^1.0.1",
    "postcss-import": "^14.0.0",
    "postcss-preset-env": "^6.7.0",
    "react": "^17.0.1",
    "react-autosize-textarea": "^7.1.0",
    "react-dom": "^17.0.1",
    "react-helmet": "^6.1.0",
    "react-hook-form": "^6.15.4",
    "react-icons": "^4.2.0",
    "react-script": "^2.0.5",
    "react-youtube": "^7.13.1"
  },
  "devDependencies": {
    "eslint": "^7.21.0",
    "eslint-config-standard": "^16.0.2",
    "eslint-config-standard-react": "^11.0.1",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.3.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-standard": "^4.1.0",
    "gatsby-plugin-postcss": "^4.0.0",
    "postcss": "^8.2.7",
    "prettier-eslint-cli": "^5.0.1",
    "prop-types": "^15.7.2"
  }

从 Gatsby v3 开始,您需要将模块作为 ES 模块导入:

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

你的情况:

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

请记住,一次导入所有样式将不允许 webpack 对您的样式进行 treeshake。首选方法是单独导入模块,如:

import { style1, style2 } from './mystyles.module.css

您可以跟踪此 GitHub thread 中讨论的堆栈跟踪。