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

Nuxt项目中Tailwind CSS使用SCSS变量报Unknown word错误如何解决?

报错根本原因

postcss-custom-properties 插件处理CSS自定义属性时,SCSS变量尚未完成编译替换,导致插件无法识别$开头的SCSS变量语法,抛出未知单词错误。


解决方案

1. 优先使用SCSS插值语法

把tailwind.scss中:root选择器内的SCSS变量统一用#{}包裹,强制SCSS先完成变量替换再交给PostCSS处理,修改后代码如下:

@import '../../brand-theme';

/* In your CSS */
:root {
  --color-primary: #{$primary};
  --color-primary-darken: #{$primary};
  --color-secondary: #{$secondary};
}

@import './layout/base';
@import './vendors/hooper';

2. 校验依赖安装

确保项目已安装SCSS编译所需依赖,未安装的话执行以下命令安装开发依赖:

npm i -D sass sass-loader

3. 修复PostCSS执行顺序(上两步无效时配置)

如果修改后仍报错,检查项目根目录postcss.config.js或nuxt.config.js中的PostCSS插件顺序,确保SCSS编译逻辑在postcss-custom-properties之前执行,Nuxt项目可参考以下配置:

// nuxt.config.js
export default {
  postcss: {
    plugins: {
      'postcss-import': {},
      'tailwindcss/nesting': {},
      tailwindcss: {},
      autoprefixer: {},
      'postcss-custom-properties': {
        preserve: true // 保留自定义属性声明,避免被提前转义
      }
    }
  }
}

4. 优化全局变量引入(可选)

如果后续多文件需要用到brand-theme.scss的变量,可安装@nuxtjs/style-resources模块自动全局注入变量,避免手动引入路径错误:

npm i -D @nuxtjs/style-resources

在nuxt.config.js中添加配置:

export default {
  modules: [
    '@nuxtjs/style-resources'
  ],
  styleResources: {
    scss: ['~/brand-theme.scss']
  }
}

配置完成后可以删掉tailwind.scss顶部的@import '../../brand-theme'语句。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:24:05