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

Gatsby 5中CSS Modules导入方式与Vitest测试的兼容问题

Gatsby 5与Vitest的CSS模块导入冲突解决

问题场景

  • Gatsby 5强制要求CSS模块使用* as语法导入,示例代码:
    import * as styles from './index.module.css'
    
    该写法在前端页面可正常渲染,但使用Vitest测试组件时,无法识别styles对象。
  • 使用旧版默认导入语法时:
    import styles from './index.module.css'
    
    Vitest测试套件能正常识别styles,但Gatsby会判定styles未定义,导致页面渲染失败。

解决方案

在Vitest的配置文件(vitest.config.ts或vite.config.ts)中,修改CSS模块的导出规则,使其支持命名导出,适配Gatsby 5的导入要求:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  css: {
    modules: {
      exportStyle: 'named'
    }
  }
})

配置完成后,使用import * as styles from './index.module.css'语法即可同时满足Gatsby 5的构建要求和Vitest的测试识别需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:12:07