Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud. Learn more

ContactSign Up
Community Plugin
View plugin on GitHub

Gatsby JssProvider Plugin

Why?

Provides drop-in support for JSS wrapping your Root element into a react-jss JssProvider.

Custom config allows you to pass custom props to the JssProvider.

Minify option allows you to enable csso minifier to compress css for SSR.

Usage

Install with npm:

npm install gatsby-plugin-jss-provider

Add to the plugin option in your gatsby config (gatsby-config.js - create it if it doesn’t exist):

module.exports = {
  plugins: ['gatsby-plugin-jss-provider'],
};

And that’s it!

Custom JssProvider props & custom Jss instance

Here’s an example using src/config/jss.js as the configuration module path.

// src/config/jss.js

const maxRules = 1e10
function createGenerateId(options) {
  let ruleCounter = 0

  return (rule) => {
    ruleCounter += 1
    
    if (ruleCounter > maxRules) {
      throw new Error(`[JSS] You might have a memory leak. Rule counter is at ${ruleCounter}.`)
    }
    
    if(options.minify){
      return `c-${ruleCounter}`
    }

    return `${rule.key}-${ruleCounter}`
  }
}

module.exports = (jss) => {
  
  // custom Jss config
  jss.setup({
      createGenerateId,
  })
  
  // custom JssProvider props 
  return {
    jss,
    generateId: jss.generateId,
  }

}

With this file created, all we need to do is modify the gatsby configuration file:

// gatsby-config.js

module.exports = {
  plugins: [{
    resolve: 'gatsby-plugin-jss-provider',
    options: {
      pathToConfigModule: 'src/config/jss.js',
    },
  }],
};

Minify

Use the minify option to enable CSS compression. Css will be minified using csso (CSS Optimizer) Advanced configuration can be passed to the minifier using the minifyConfig option (see available options)

// gatsby-config.js

module.exports = {
  plugins: [{
    resolve: 'gatsby-plugin-jss-provider',
    options: {
      minify: true,
      minifyConfig: {
        restructure: false,
        comments: false,
      },
    },
  }],
};

Troubleshooting

If you have any issues, raise an issue in the bug tracker! Alternatively, feel free to fix and create a PR ;)

Inspiration

Thank you to gatsby-plugin-jss and gatsby-plugin-better-jss for inspiration

© 2024 Gatsby, Inc.