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

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

profile

Jasneet Sawhney

4/6/2021

Firstly define the pages you want to use amp for, by deaclaring

```

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.