Skip to content

Instantly share code, notes, and snippets.

@giuseppeg
Last active February 16, 2023 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuseppeg/15425f8ab3cdf8e5ee964d1edf537115 to your computer and use it in GitHub Desktop.
Save giuseppeg/15425f8ab3cdf8e5ee964d1edf537115 to your computer and use it in GitHub Desktop.
Incremental TailwindCSS on Next.js
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>;
}
// 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