Search code examples
sassgatsbypostcss

Howto add PostCSS plugin to the Gatsby SASS plugin


I have a Gatsby site with sass support using the gatsby-plugin-sass plugin. That works, but now I want to add PostCSS support.

According to the warning on this page (a deprecated plugin) this now should be possible by defining the postcss plugin in the postCssPlugins options.

Indeed, the sass plugin documentation tells me I can add a postcss plugin to the options, but it's unclear to me how to do this exactly. I already added the gatsby-plugin-postcss plugin separately and am now trying to integrate it with the sass plugin.

This does not work:

gatsby-config.js:

    // SASS support with PostCSS support:
    `gatsby-plugin-postcss`,
    {
      resolve: `gatsby-plugin-sass`,
      options: {
        postCssPlugins: ['gatsby-plugin-postcss'],
      },
    },

I guess I should call it in a different way but I can't find any documentation on this?


Solution

  • gatsby-plugin-postcss use specific postcss plugin(postcss-preset-env, for example) to handle css code, itself is not a postcss plugin, so you can't use it in postCssPlugins option.

    And the pipeline for gastby to handle sass file is sass -> postcss plugin -> final result, so just use sass plugin and choose postcss in its option postCssPlugins.

    {
      resolve: `gatsby-plugin-sass`,
      options: {
        postCssPlugins: [
          require(`postcss-preset-env`)({
            stage: 2,
            features: {
              "nesting-rules": true,
            },
          }),
        ],
        precision: 6,
      },
    },