Skip to content

Commit

Permalink
Ensure that tailwind utils override component styling
Browse files Browse the repository at this point in the history
  • Loading branch information
jeppester committed Nov 14, 2023
1 parent 41ccdf8 commit 48055d3
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
10 changes: 9 additions & 1 deletion .storybook/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const path = require("path")
const { cascadeLayerPrefixer } = require("../utils/cascadeLayerPrefixer")

module.exports = {
stories: ["../stories/Introduction.stories.mdx", "../stories/**/*stories*"],
Expand Down Expand Up @@ -49,7 +50,14 @@ module.exports = {
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [require("tailwindcss"), require("autoprefixer")],
plugins: [
require("tailwindcss"),
cascadeLayerPrefixer({
layerName: "components",
fileNameMatcher: /\/components\/.+/,
}),
require("autoprefixer"),
],
},
},
},
Expand Down
13 changes: 9 additions & 4 deletions main.scss
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
/* Provide sufficient contrast against white background */
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer tailwind-base, components, tailwind-utils;

@layer tailwind-base {
@tailwind base;
}
@layer tailwind-utils {
@tailwind components;
@tailwind utilities;
}

@font-face {
font-family: "Inter";
Expand Down
28 changes: 28 additions & 0 deletions utils/cascadeLayerPrefixer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const postcss = require("postcss")
/* eslint-enable @typescript-eslint/no-var-requires */

// PostCSS plugin for wrapping matching CSS files in a cascade layer
export const cascadeLayerPrefixer = ({ fileNameMatcher, layerName } = {}) => ({
postcssPlugin: "postcss-layer",
Once(root) {
// Ignore files that don't match the file matcher
if (!fileNameMatcher?.test(root.source.input.file)) {
return
}

// Create a new layer rule
const layerRule = postcss.atRule({ name: "layer", params: layerName })

// Move all other rules into the layer rule
root.each((node) => {
// Only actual rules (not atrules)
if (node.type === "rule") {
layerRule.append(node)
}
})

// Append layer rule
root.append(layerRule)
},
})

0 comments on commit 48055d3

Please sign in to comment.