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

如何在Vite中配置styled-jsx支持嵌套类、Tailwind指令及PostCSS?

在Vite中配置styled-jsx支持Tailwind指令与嵌套类

解决步骤:

  1. 安装全部必要依赖
    确保安装所有需要的开发依赖:

    npm install styled-jsx styled-jsx-plugin-postcss tailwindcss postcss-nesting postcss-preset-env autoprefixer --save-dev
    
  2. 修正Vite配置中的Babel插件写法
    你之前的错误在于把styled-jsx-plugin-postcss作为独立Babel插件配置,实际上它是styled-jsx的子插件,需要嵌套在styled-jsx/babel的配置对象里。修改后的vite.config.js如下:

    import { defineConfig } from "vite";
    import react from "@vitejs/plugin-react";
    
    export default defineConfig({
      plugins: [
        react({
          babel: {
            plugins: [
              [
                "styled-jsx/babel",
                {
                  plugins: ["styled-jsx-plugin-postcss"]
                }
              ]
            ],
          },
        }),
      ],
    });
    
  3. 保留现有PostCSS配置
    你的postcss.config.cjs配置完全正确,无需修改:

    module.exports = {
      plugins: {
        'tailwindcss/nesting': 'postcss-nesting',
        'postcss-preset-env': {
          stage: 1
        },
        tailwindcss: {},
        autoprefixer: {},
      }
    }
    

验证配置是否生效

在React组件中编写测试代码,确认Tailwind指令和嵌套类正常工作:

function App() {
  return (
    <div className="app-container">
      <h1>Styled-JSX + Tailwind in Vite</h1>
      <style jsx>{`
        .app-container {
          @apply max-w-4xl mx-auto p-6;
        }
        .app-container h1 {
          @apply text-2xl font-bold text-gray-800;
          @screen md {
            @apply text-3xl text-blue-600;
          }
        }
      `}</style>
    </div>
  );
}

export default App;

启动Vite开发服务后,样式会按预期编译生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:48:21