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

如何让Vite将style.css作为真实CSS文件并获取Tailwind计算类?

问题描述

我有一个基于Vite(原生)、TypeScript和TailwindCSS的项目,其中包含自定义元素代码如下。当前Vite开发服务器把style.css当作JS文件提供服务,请问怎么从Vite开发服务器获取计算后的Tailwind类?


自定义元素代码(CardComponent)

import {globalStyleSheet} from '../styles/global-style-sheet.ts';

class CardComponent extends HTMLElement {
  static get observedAttributes() {
    return ['header', 'text'];
  }
  
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    (this.shadowRoot as ShadowRoot).adoptedStyleSheets = [globalStyleSheet];
    this.render();
  }

  attributeChangedCallback() {
    this.render();
  }

  render() {
     const header = this.getAttribute('header') || '';
     const text = this.getAttribute('text') || '';
     this.shadowRoot!.innerHTML = ` 
       <div class="max-w-sm rounded overflow-hidden shadow-lg bg-white p-6">
         <div class="font-bold text-xl mb-2">${header}</div>
         <p class="text-gray-700 text-base">${text}</p>
       </div>
     `;
  }
}

customElements.define('card-component', CardComponent);

global-style-sheet.ts

import globalCss from '../style.css?raw'
    
const cssStyleSheet = new CSSStyleSheet();
cssStyleSheet.replaceSync(globalCss);
export const globalStyleSheet = cssStyleSheet;

style.css

@import "tailwindcss";

:root {
  font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
  line-height: 1.5;
  font-weight: 400; 
  color-scheme: light dark; 
  font-synthesis: none;
  text-rendering: optimizeLegibility; 
}

项目依赖

{
  "dependencies": {
    "@tailwindcss/vite": "^4.1.11",
    "@types/node": "^24.0.7",
    "tailwindcss": "^4.1.11",
    "typescript": "~5.8.3",
    "vite": "^7.0.0"
  }
}

解决方法

问题核心是用?raw导入CSS时,Vite跳过了Tailwind的编译流程,直接返回原始文件内容。要获取计算后的Tailwind类,按以下步骤调整:

  1. 修改CSS导入方式
    将?raw替换为?inline,让Vite先完成Tailwind编译再返回处理后的CSS内容:

    import globalCss from '../style.css?inline';
    
    const cssStyleSheet = new CSSStyleSheet();
    cssStyleSheet.replaceSync(globalCss);
    export const globalStyleSheet = cssStyleSheet;
    
  2. 确认Vite配置集成Tailwind
    确保vite.config.ts中正确注册Tailwind插件:

    import { defineConfig } from 'vite';
    import tailwindcss from '@tailwindcss/vite';
    
    export default defineConfig({
      plugins: [tailwindcss()],
    });
    
  3. 让Tailwind扫描自定义元素中的类
    在tailwind.config.ts的content数组中添加自定义元素文件路径,确保Tailwind能检测到用到的工具类:

    import { defineConfig } from 'tailwindcss';
    
    export default defineConfig({
      content: [
        './src/**/*.{html,ts,js}',
        './src/components/**/*.ts', // 明确指向自定义元素所在目录
      ],
      // 其他配置...
    });
    
  4. 重启开发服务器验证
    重启Vite后,globalStyleSheet会包含编译后的Tailwind工具类,自定义元素的Shadow DOM即可正确应用样式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:52:16