You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gatsby应用无法导入CSS模块:找不到.module.css模块或类型声明

解决Gatsby中CSS模块导入报错Cannot find module '[your-filename].module.css'的问题
  • 检查文件命名与路径
    确保CSS文件严格遵循[name].module.css命名格式,比如Layout.module.css,文件名大小写要和导入语句完全匹配(Gatsby对大小写敏感)。同时确认文件实际存在于你指定的导入路径下,比如导入./components/Layout.module.css时,要检查src/components/Layout.module.css是否存在。

  • 验证导入语法
    导入CSS模块的语法必须正确,示例如下:

    import styles from './Layout.module.css'
    

    不要省略.module.css后缀,路径分隔符统一用/,避免使用系统相关的\。

  • 处理TypeScript类型声明(若使用TS)
    如果项目基于TypeScript,需要手动添加CSS模块的类型声明:

    1. 在src目录下创建declarations.d.ts文件
    2. 添加以下代码:
      declare module '*.module.css' {
        const classes: { [key: string]: string }
        export default classes
      }
      

    保存后重启开发服务器,TypeScript即可识别CSS模块类型。

  • 清除Gatsby缓存并重启服务
    缓存可能导致文件变更未被识别,执行以下命令:

    gatsby clean
    gatsby develop
    
  • 确认Gatsby版本兼容性
    CSS模块在Gatsby v4及以上版本才支持开箱即用,执行gatsby --version查看版本,若版本过低,升级到最新稳定版:

    npm install gatsby@latest
    

内容的提问来源于stack exchange,提问作者KyleMo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:24:55