带有 PostCSS 8 的 Gatsby - 尝试导入错误:“component.module.css”不包含默认导出作为“样式”导入

问题描述

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

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

尝试导入错误:“[componentName].module.css”不包含认导出(作为“样式”导入)

当我在 react 组件中导入 css 文件

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

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

这是我的 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 中,您需要将模块导入为:

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

就你而言:

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

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

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

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