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

如何在Vite搭建的React项目中导入样式时省略.module后缀

解决Vite中省略.module后缀导入SCSS模块的问题

问题背景

我用SASS搭建了基于Vite的React新项目,之前Webpack项目里可以直接这样导入样式文件(无需.module后缀):

import style from './styles/MyComponent.scss';

// 在JSX中使用样式
<p className={style.myParagraph}>

但Vite抛出了错误:

Default and named imports from CSS files are deprecated. Use the ?inline query instead. For example: import style from "./styles/MyComponent.scss?inline"

当前我的vite.config.js配置如下:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  css: {
    modules: {
      include: /\.scss$/,
      scopeBehaviour: 'local',
      localsConvention: 'camelCase'
    },
    preprocessorOptions: {
      scss: {
        include: /\.scss$/,
        localsConvention: 'camelCase'
      }
    },
  },
  build: {
    cssCodeSplit: false,
    minify: true,
  },
})

解决方案

问题根源在于Vite默认仅将带.module后缀的文件识别为CSS模块,你需要调整配置让所有.scss文件都被当作CSS模块处理,但必须排除全局样式文件(比如全局重置、公共样式),避免样式被局部作用域哈希污染。

修改后的vite.config.js配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  css: {
    modules: {
      // 匹配所有.scss文件作为CSS模块
      include: /\.scss$/,
      // 若有全局样式,用exclude排除(示例:排除styles/global下的所有scss文件)
      // exclude: /styles\/global\/.+\.scss$/
      scopeBehaviour: 'local',
      localsConvention: 'camelCase'
    },
    preprocessorOptions: {
      scss: {
        // 这里可以配置Sass全局变量导入,比如:
        // additionalData: `@import "./src/styles/variables.scss";`
      }
    },
  },
  build: {
    cssCodeSplit: false,
    minify: true,
  },
})

核心要点

  1. css.modules.include:设置为/\.scss$/后,Vite会把所有.scss文件当作CSS模块处理,无需.module后缀即可通过命名导入使用。
  2. 全局样式排除:如果项目存在全局样式,一定要用exclude规则过滤,否则全局样式会被添加局部作用域标识,导致样式失效。
  3. 清理冗余配置:删除preprocessorOptions.scss中的include和localsConvention,这两个不属于Sass预处理器的配置项,完全多余。

修改完成后,你就能像之前Webpack项目那样正常导入并使用SCSS样式模块了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:05:31