Search code examples
next.jsstyled-componentstailwind-csstailwind-in-js

how to import tailwind inside 'createGlobalStyle'


I'm trying to import tailwind inside my styled components globalstyle, to set base styles.

Code below doesn't work, so any suggestions on how to make it work?

import {createGlobalStyle} from 'styled-components';


const GlobalStyle = createGlobalStyle`
  @tailwind base;
  @tailwind components;
  @tailwind utilities;
  
  @layer base {
    h1 {
      @apply text-2xl;
    }
    h2 {
      @apply text-xl;
    }
  }
`

Solution

  • Try twin.macro !!~~~

    Click here!

    // src/styles/GlobalStyles.js
    import React from 'react'
    import { createGlobalStyle } from 'styled-components'
    import tw, { theme, GlobalStyles as BaseStyles } from 'twin.macro'
    
    const CustomStyles = createGlobalStyle`
      body {
        -webkit-tap-highlight-color: ${theme`colors.purple.500`};
        ${tw`antialiased`}
      }
    `
    
    const GlobalStyles = () => (
      <>
        <BaseStyles />
        <CustomStyles />
      </>
    )
    
    export default GlobalStyles
    

    Add the twin config

    // babel-plugin-macros.config.js
    module.exports = {
      twin: {
        preset: 'styled-components',
      },
    }