or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Gatsby Plugin Styled Components

Gatsby Plugin Styled Components provides seamless integration of styled-components into Gatsby applications with automatic server-side rendering support. The plugin handles the complex setup of collecting and injecting CSS styles during SSR while providing comprehensive configuration options for development and production optimization.

Package Information

  • Package Name: gatsby-plugin-styled-components
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install gatsby-plugin-styled-components styled-components babel-plugin-styled-components

Core Imports

This is a Gatsby plugin that is configured in gatsby-config.js rather than imported directly in application code.

// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: "gatsby-plugin-styled-components",
      options: {
        // Plugin configuration options
      },
    },
  ],
};

Basic Usage

// gatsby-config.js - Basic configuration
module.exports = {
  plugins: ["gatsby-plugin-styled-components"],
};

// gatsby-config.js - With options
module.exports = {
  plugins: [
    {
      resolve: "gatsby-plugin-styled-components",
      options: {
        displayName: true,
        fileName: true,
        minify: true,
        namespace: "my-app",
        pure: false,
        transpileTemplateLiterals: true,
        disableVendorPrefixes: false,
      },
    },
  ],
};

Once configured, use styled-components normally in your Gatsby components:

import styled from "styled-components";

const Button = styled.button`
  background: ${props => props.primary ? "blue" : "white"};
  color: ${props => props.primary ? "white" : "blue"};
`;

const MyComponent = () => (
  <div>
    <Button>Normal Button</Button>
    <Button primary>Primary Button</Button>
  </div>
);

Architecture

The plugin implements a dual-environment architecture to support both server-side rendering and client-side hydration:

  • Build-time Configuration: Uses Gatsby's onCreateBabelConfig API to configure babel-plugin-styled-components with appropriate settings for each build stage
  • Server-side Rendering (SSR): Implements wrapRootElement and onRenderBody in gatsby-ssr.js to collect styles during SSR and inject them into the document head
  • Client-side Hydration: Uses wrapRootElement in gatsby-browser.js to provide StyleSheetManager for proper client-side styled-components behavior
  • Style Collection: Maintains a Map of ServerStyleSheet instances keyed by pathname to handle multiple pages during SSR
  • Vendor Prefixing: Conditionally applies vendor prefixes based on the disableVendorPrefixes option through StyleSheetManager

Capabilities

Plugin Configuration

Configure the babel-plugin-styled-components through Gatsby's plugin system.

interface PluginOptions {
  /** 
   * Enhances CSS class names with component names for debugging.
   * Changes <button class="asdf123" /> to <button class="Button-asdf123 asdf123" />
   */
  displayName?: boolean; // default: true
  
  /** Prefixes the displayName with the filename */
  fileName?: boolean; // default: true
  
  /** Removes whitespace from generated CSS */
  minify?: boolean; // default: true
  
  /** 
   * Ensures unique class names, useful for micro frontends 
   * to prevent class name collisions 
   */
  namespace?: string; // default: ""
  
  /** Transpiles tagged template literals into optimized code */
  transpileTemplateLiterals?: boolean; // default: true
  
  /** Top level import paths allowed to identify styled-components library */
  topLevelImportPaths?: string[]; // default: []
  
  /** 
   * Enables "pure annotations" for better dead code elimination by minifiers.
   * Tells minifiers that styled components have no side effects.
   */
  pure?: boolean; // default: false
  
  /** Disables vendor prefixing in CSS output */
  disableVendorPrefixes?: boolean; // default: false
}

Server-Side Rendering Setup

The plugin automatically configures styled-components for SSR in Gatsby applications. This involves:

  1. Style Collection: During SSR, styles are collected using ServerStyleSheet
  2. Style Injection: Collected styles are injected into the document head
  3. Hydration: Client-side hydration works seamlessly with server-rendered styles
// Gatsby SSR API - wrapRootElement (Server-side)
function wrapRootElement(
  { element, pathname }: { element: React.ReactElement; pathname: string },
  pluginOptions: PluginOptions
): React.ReactElement;

// Gatsby SSR API - onRenderBody
function onRenderBody(
  { setHeadComponents, pathname }: { 
    setHeadComponents: (components: React.ReactElement[]) => void; 
    pathname: string; 
  }
): void;

Client-Side Setup

The plugin also handles client-side setup for styled-components.

// Gatsby Browser API - wrapRootElement (Client-side)
function wrapRootElement(
  { element }: { element: React.ReactElement },
  pluginOptions: PluginOptions
): React.ReactElement;

Babel Plugin Integration

The plugin automatically configures babel-plugin-styled-components based on the build stage.

// Gatsby Node API - onCreateBabelConfig
function onCreateBabelConfig(
  { stage, actions }: { 
    stage: string; 
    actions: { setBabelPlugin: Function }; 
  },
  pluginOptions: PluginOptions
): void;

// Gatsby Node API - pluginOptionsSchema
function pluginOptionsSchema(
  { Joi }: { Joi: typeof import('joi') }
): import('joi').ObjectSchema;

Plugin Options

displayName

Type: boolean
Default: true

Enhances CSS class names with component names for easier debugging. When enabled, class names include both the component name and hash.

Example:

  • Disabled: <button class="sc-bdVaJa dQwYZf" />
  • Enabled: <button class="Button-sc-bdVaJa-gQjmmi dQwYZf" />

fileName

Type: boolean
Default: true

Prefixes the displayName with the filename where the styled component is defined.

minify

Type: boolean
Default: true

Removes whitespace and optimizes the generated CSS for production builds.

namespace

Type: string
Default: ""

Adds a namespace prefix to all class names. Useful for micro-frontend architectures where multiple applications might have conflicting styled-components.

Example: With namespace "my-app", class names become my-app__Button-sc-bdVaJa

transpileTemplateLiterals

Type: boolean
Default: true

Transpiles styled-components template literals into more optimized JavaScript code for better runtime performance.

topLevelImportPaths

Type: string[]
Default: []

Specifies additional import paths that should be treated as styled-components imports. Useful when using custom builds or alternative distributions.

pure

Type: boolean
Default: false

Adds "pure" annotations to styled component functions, helping minifiers perform better dead code elimination by indicating these functions have no side effects.

disableVendorPrefixes

Type: boolean
Default: false

Disables automatic vendor prefixing in the generated CSS. When enabled, you're responsible for adding vendor prefixes manually or through other tools.

Build Stage Handling

The plugin automatically detects the build stage and configures babel-plugin-styled-components appropriately:

  • Development stages: develop, develop-html
  • Production stages: build-javascript, build-html
  • SSR detection: Automatically enables SSR options for build-html and build-javascript stages

Error Handling

The plugin validates that required peer dependencies are installed:

interface RequiredPeerDependencies {
  "babel-plugin-styled-components": ">1.5.0";
  "gatsby": "^5.0.0-next";
  "react": "^18.0.0 || ^0.0.0";
  "react-dom": "^18.0.0 || ^0.0.0";
  "styled-components": ">=2.0.0";
}

If babel-plugin-styled-components is not installed, the plugin throws a clear error message with installation instructions.

TypeScript Support

The plugin works with TypeScript projects out of the box. Styled-components TypeScript definitions are provided by the styled-components package itself.

// Works automatically with TypeScript
import styled from "styled-components";

interface ButtonProps {
  primary?: boolean;
  size?: "small" | "medium" | "large";
}

const Button = styled.button<ButtonProps>`
  background: ${props => props.primary ? "blue" : "white"};
  color: ${props => props.primary ? "white" : "blue"};
  padding: ${props => 
    props.size === "small" ? "4px 8px" :
    props.size === "large" ? "12px 24px" :
    "8px 16px"
  };
`;

Compatibility

  • Gatsby: ^5.0.0-next
  • React: ^18.0.0
  • Node.js: >=18.0.0
  • styled-components: >=2.0.0
  • babel-plugin-styled-components: >1.5.0