Last active
February 16, 2023 22:01
-
-
Save giuseppeg/15425f8ab3cdf8e5ee964d1edf537115 to your computer and use it in GitHub Desktop.
Incremental TailwindCSS on Next.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Head from "next/head"; | |
import * as React from "react"; | |
import "../styles/global.css"; | |
export default function MyApp({ Component, pageProps }) { | |
/* | |
Page components can add the tw property to the component page to enable Tailwind, eg: | |
AboutPage.tw = true; | |
export default function AboutPage { ... } | |
*/ | |
const Wrapper = Component.tw === true ? WithTw : React.Fragment; | |
return ( | |
<> | |
<Head> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<style>{`body{ margin:0 }`}</style> | |
</Head> | |
<Wrapper> | |
<Component {...pageProps} /> | |
</Wrapper> | |
</> | |
); | |
} | |
function WithTw({ children }) { | |
return <div className="tw">{children}</div>; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// probably you can load the prefix from tailwind's config (important property) | |
module.exports = (opts = { prefix: ".tw" }) => { | |
return { | |
postcssPlugin: "twprefix", | |
Rule(rule) { | |
rule.selectors = rule.selectors.map((s) => { | |
// @todo add check for valid selectors | |
if (s.startsWith(opts.prefix) || /^[0-9]/.test(s)) { | |
return s; | |
} | |
return `${opts.prefix} ${s}`; | |
}); | |
}, | |
}; | |
}; | |
module.exports.postcss = true; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment