使用PostCSS时.css文件无法渲染嵌套类及伪类问题
使用PostCSS时CSS文件无法渲染嵌套类与伪类
在使用PostCSS配合Tailwind CSS时,自定义CSS中的嵌套类(如&:hover)和伪类样式无法正常渲染生效。相关配置及代码如下:
配置文件与代码
tw-imports.css
@tailwind base; @tailwind components; @tailwind utilities;
tailwind.config.js
const { createGlobPatternsForDependencies } = require('@nrwl/angular/tailwind'); const { join } = require('path'); module.exports = { mode: 'jit', content: [ join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'), ...createGlobPatternsForDependencies(__dirname), ], darkMode: 'media', theme: { extend: {}, }, plugins: [], };
postcss.config.js
module.exports = { plugins: [ 'postcss-import', 'tailwindcss', 'postcss-flexbugs-fixes', 'postcss-nested', 'postcss-custom-properties', 'autoprefixer', [ 'postcss-preset-env', { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': true, 'nesting-rules': true, }, }, ], ], }
自定义CSS代码
.button { @apply rounded text-slate-500 ring-slate-900/5 shadow p-3 ring-2; &:hover { --mainColor: #b3a5c0; color: var(--mainColor); } }
.storybook/main.js
module.exports = { stories: [], addons: [ '@storybook/addon-essentials', { name: '@storybook/addon-postcss', options: { postcssLoaderOptions: { implementation: require('postcss'), } } } ], core: { builder: 'webpack5', }, // uncomment the property below if you want to apply some webpack config globally webpackFinal: async (config, { configType }) => { // Make whatever fine-grained changes you need that should apply to all storybook configs // Return the altered config return config; }, };
问题现象
样式未正常生效,截图如下:
解决方案
1. 调整PostCSS插件执行顺序
PostCSS插件执行顺序直接影响解析结果,处理嵌套规则的插件需要在tailwindcss之前运行,这样Tailwind才能正确识别嵌套语法。修改postcss.config.js:
module.exports = { plugins: [ 'postcss-import', // 优先处理嵌套规则,二选一即可 ['postcss-preset-env', { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': true, 'nesting-rules': true, }, }], // 'postcss-nested', 'tailwindcss', 'postcss-flexbugs-fixes', 'postcss-custom-properties', 'autoprefixer', ], };
2. 让Storybook读取项目PostCSS配置
Storybook的PostCSS插件默认可能不会自动加载项目根目录的配置,需要显式指定路径。修改.storybook/main.js:
module.exports = { stories: [], addons: [ '@storybook/addon-essentials', { name: '@storybook/addon-postcss', options: { postcssLoaderOptions: { implementation: require('postcss'), config: { path: require.resolve('../postcss.config.js') } } } } ], core: { builder: 'webpack5', }, webpackFinal: async (config, { configType }) => { return config; }, };
3. 扩展Tailwind JIT模式的扫描范围
Tailwind JIT模式需要扫描所有使用样式的文件,确保自定义CSS文件被纳入扫描范围。修改tailwind.config.js的content字段:
content: [ join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html,css}'), // 添加css后缀 ...createGlobPatternsForDependencies(__dirname), ],
4. 确认自定义CSS的引入方式
确保自定义CSS文件已正确引入到项目中(比如在全局样式文件中通过@import引入,或在组件内导入),否则PostCSS无法对其进行处理。
内容的提问来源于stack exchange,提问作者hackp0int
相关产品推荐
相关产品推荐

