Logo
Home

What are AMP sites? And how to use them with Next.js and Tailwindcss?

some good alt text
Web DevelopmentTechnology

About the author

Jasneet is a web developer and renaissance polymath. A coding buff with an instinct of building products through first principles and distributing among multitudes.

profile

Jasneet Sawhney

4/6/2021

Firstly define the pages you want to use the amp for, by declaring
export const config = { amp: true }
Move to _document.js
import tailwindcss from '!raw-loader!../styles/tailwind.min.css';
import Document, { Head, Html, Main, NextScript } from 'next/document';
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const page = ctx.renderPage((App) => (props) => <App {...props} />);
const initialProps = await Document.getInitialProps(ctx);
return {
...page,
styles: [
...initialProps.styles,
<style
key="custom"
dangerouslySetInnerHTML={{ __html: tailwindcss, }} />, ], }; } render() { return ( <Html> <Head> </Head> <body> <Main /> <NextScript /> </body> </Html> )}}
Now by default, you won't be having the raw-loader library, so download it by installing
yarn add raw-loader
Now your app will work smoothly in the development environment, but we have to do some extra work so that it works in production.
First, let's declare an environment variable.
CSS_ENV=build postcss styles/globals.css --config postcss.config.js -o styles/output.css
Now, in postcss.config.js
// postcss.config.jsconst purgecssOption = { // Specify the paths to all of the template files in your project content: [ './pages/**/*.{js,jsx,ts,tsx}', './components/**/*.{js,jsx,ts,tsx}' ], // Include any special characters you're using in this regular expression defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []}; module.exports = { plugins: process.env.CSS_ENV === 'build' ? [ require('tailwindcss'), require('@fullhuman/postcss-purgecss')(purgecssOption), require('postcss-preset-env'), require('cssnano')({ preset: 'default' }) ] : [ 'tailwindcss', process.env.NODE_ENV === 'production' ? ['@fullhuman/postcss-purgecss', purgecssOption] : undefined, 'postcss-preset-env' ]};
Also, change _document.js as:
// pages/_document.jsimport outputcss from '!raw-loader!../styles/output.css';import tailwindcss from '!raw-loader!../styles/tailwind.min.css';const cssFile = process.env.NODE_ENV === 'production' ? outputcss : tailwindcss; export default class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: ( <> <style dangerouslySetInnerHTML={{ __html: cssFile }} /> {initialProps.styles} </> ) }; } render() {...}}
Done!! Voila, now you can deploy it.