1. Installation
  2. Install Tailwind CSS with Gatsby
  1. Create your project

    Start by creating a new Gatsby project if you don’t have one set up already. The most common approach is to use Gatsby CLI.

    Terminal
    gatsby new my-projectcd my-project
  2. Install Tailwind CSS

    Using npm, install tailwindcss and its peer dependencies, as well as gatsby-plugin-postcss, and then run the init command to generate both tailwind.config.js and postcss.config.js.

    Terminal
    npm install -D tailwindcss postcss autoprefixer gatsby-plugin-postcssnpx tailwindcss init -p
  3. Enable the Gatsby PostCSS plugin

    In your gatsby-config.js file, enable the gatsby-plugin-postcss. See the plugin's documentation for more information.

    gatsby-config.js
    module.exports = {
      plugins: [
        'gatsby-plugin-postcss',
        // ...
      ],
    }
    
  4. Configure your template paths

    Add the paths to all of your template files in your tailwind.config.js file.

    tailwind.config.js
    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        "./src/pages/**/*.{js,jsx,ts,tsx}",
        "./src/components/**/*.{js,jsx,ts,tsx}",
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }
    
  5. Add the Tailwind directives to your CSS

    Create a ./src/styles/global.css file and add the @tailwind directives for each of Tailwind’s layers.

    global.css
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
  6. Import the CSS file

    Create a gatsby-browser.js file at the root of your project if it doesn’t already exist, and import your newly-created ./src/styles/global.css file.

    gatsby-browser.js
    import './src/styles/global.css'
    
  7. Start your build process

    Run your build process with gatsby develop.

    Terminal
    gatsby develop
  8. Start using Tailwind in your project

    Start using Tailwind’s utility classes to style your content.

    index.js
    export default function IndexPage() {
      return (
        <Layout>
          <h1 className="text-3xl font-bold underline">
            Hello world!
          </h1>
        </Layout>
      )
    }
    

Tailwind CSS 中文网 - 粤ICP备13048890号