Gatsby 3.0.1 配置gatsby-plugin-sass后SCSS Module导入报错
Gatsby 3 Sass CSS Module 报错排查方案
核心原因
报错本质是webpack未将.module.scss文件识别为CSS Module,或是导入路径存在笔误,导致无法导出对应样式对象。
分步排查修复
- 匹配对应版本的依赖
Gatsby 3.0.1 不兼容最新版的gatsby-plugin-sass,新版插件仅适配Gatsby 4+版本,导出逻辑变更后就会出现无样式对象可导入的问题。需要安装适配Gatsby 3的稳定版本:
不要默认安装最新版的npm install gatsby-plugin-sass@4.14.0 sass@1.32.8gatsby-plugin-sass。 - 修正导入路径笔误
你测试的第二种导入写法存在路径错误:'../styles/scss/index/module.scss'将文件名的.误写为/,正确文件路径是'../styles/scss/index.module.scss',路径错误会导致webpack无法解析对应文件,自然识别不到类名导出。 - 确认文件命名规则
当前gatsby-plugin-sass的默认逻辑是:只有后缀为.module.scss/.module.sass的文件才会被识别为CSS Module,导出类名对应的哈希对象;普通.scss文件仅作为全局样式注入,不会导出任何对象。你当前的样式文件命名符合规则,无需调整。 - 清空编译缓存重启
修改依赖和配置后,需要先执行gatsby clean删除本地Gatsby编译缓存,再重新启动开发服务,避免旧缓存导致的报错残留。
正确的代码示例
gatsby-config.js 配置
module.exports = { plugins: [ { resolve: `gatsby-plugin-sass`, options: { implementation: require("sass"), }, }, ], }
页面导入写法
import React from "react" import homeStyles from '../styles/scss/index.module.scss' export default function Home() { return <div className={homeStyles.testElement}>Hello world!</div> }
样式文件
.testElement { font-size: 72px; }
报错对应说明
「
../styles/scss/index.module.scssdoes not contain a default export」:是因为webpack将该文件识别为了普通全局样式,全局样式不会导出任何对象,因此默认导入无法拿到值。
「'testElement' is not exported from '../styles/scss/index.module.scss'」:是因为导入路径笔误,webpack未成功解析目标CSS Module文件,自然无法识别其中定义的类名导出。
内容的提问来源于stack exchange,提问作者CircularRecursion
相关产品推荐
相关产品推荐

