如何在Vite中配置styled-jsx支持嵌套类、Tailwind指令及PostCSS?
在Vite中配置styled-jsx支持Tailwind指令与嵌套类
解决步骤:
安装全部必要依赖
确保安装所有需要的开发依赖:npm install styled-jsx styled-jsx-plugin-postcss tailwindcss postcss-nesting postcss-preset-env autoprefixer --save-dev修正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"] } ] ], }, }), ], });保留现有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
相关产品推荐
相关产品推荐

