gatsby: [v2] gatsby - Duplicate styles when serving site

Description

Seeing duplicate style declarations when serving the site.

Not sure if this is a webpack issue or not?

Steps to reproduce

screen shot 2018-08-21 at 14 14 32

Environment

System: OS: macOS High Sierra 10.13.5 CPU: x64 Intel® Core™ i5-6267U CPU @ 2.90GHz Shell: 5.3 - /bin/zsh Binaries: Node: 9.2.0 - ~/.nvm/versions/node/v9.2.0/bin/node Yarn: 1.6.0 - ~/.nvm/versions/node/v9.2.0/bin/yarn npm: 5.8.0 - ~/.nvm/versions/node/v9.2.0/bin/npm Browsers: Chrome: 68.0.3440.106 Firefox: 60.0.2 Safari: 11.1.1 npmPackages: gatsby: next => 2.0.0-rc.0 gatsby-image: next => 2.0.0-rc.0 gatsby-plugin-catch-links: next => 2.0.2-rc.0 gatsby-plugin-manifest: next => 2.0.2-rc.0 gatsby-plugin-netlify: next => 2.0.0-rc.0 gatsby-plugin-nprogress: next => 2.0.0-rc.0 gatsby-plugin-offline: next => 2.0.0-rc.0 gatsby-plugin-react-helmet: next => 3.0.0-rc.0 gatsby-plugin-sass: next => 2.0.0-rc.0 gatsby-plugin-sharp: next => 2.0.0-rc.0 gatsby-source-contentful: next => 2.0.1-rc.0 gatsby-transformer-remark: next => 2.1.1-rc.0 gatsby-transformer-sharp: next => 2.1.1-rc.0 npmGlobalPackages: gatsby-cli: 1.1.58

File contents (if changed)

gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: `davidrich.es`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-sass`,
    `gatsby-transformer-remark`,
    `gatsby-plugin-catch-links`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: "David Riches 🏑",
        short_name: "DR 🏑",
        start_url: "/",
        background_color: "#ffffff",
        theme_color: "#A864A8",
        display: "minimal-ui",
        icons: [
          {
            src: `/favicons/android-chrome-192x192.png`,
            sizes: `192x192`,
            type: `image/png`,
          },
          {
            src: `/favicons/android-chrome-512x512.png`,
            sizes: `512x512`,
            type: `image/png`,
          },
        ],
      },
    },
    `gatsby-plugin-offline`,
      {
        resolve: `gatsby-source-contentful`,
          options: {
            spaceId: `anjlutb8dq3v`,
            accessToken: `4bf9314dc5bdfbf380247aa3ab84d7da0e86d33a6089168eb32558d4f7096cda`
          },
      },
      {
        resolve: `gatsby-plugin-netlify`,
          options: {
            headers: {}, // option to add more headers. `Link` headers are transformed by the below criteria
            allPageHeaders: [], // option to add headers for all pages. `Link` headers are transformed by the below criteria
            mergeSecurityHeaders: true, // boolean to turn off the default security headers
            mergeLinkHeaders: true, // boolean to turn off the default gatsby js headers
            mergeCachingHeaders: true, // boolean to turn off the default caching headers
            transformHeaders: (headers, path) => headers, // optional transform for manipulating headers under each path (e.g.sorting), etc.
            generateMatchPathRewrites: true, // boolean to turn off automatic creation of redirect rules for client only paths
        },
      },
  ],
}

package.json:

{
  "name": "gatsby-starter-default",
  "description": "Gatsby default starter",
  "version": "1.0.0",
  "author": "Kyle Mathews <mathews.kyle@gmail.com>",
  "dependencies": {
    "gatsby": "next",
    "gatsby-image": "next",
    "gatsby-plugin-catch-links": "next",
    "gatsby-plugin-manifest": "next",
    "gatsby-plugin-netlify": "next",
    "gatsby-plugin-nprogress": "next",
    "gatsby-plugin-offline": "next",
    "gatsby-plugin-react-helmet": "next",
    "gatsby-plugin-sass": "next",
    "gatsby-plugin-sharp": "next",
    "gatsby-source-contentful": "next",
    "gatsby-transformer-remark": "next",
    "gatsby-transformer-sharp": "next",
    "node-sass": "^4.9.0",
    "react": "^16.4.1",
    "react-anchor-link-smooth-scroll": "^1.0.10",
    "react-dom": "^16.4.1",
    "react-helmet": "^5.2.0",
    "typeface-karla": "0.0.54"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "main": "n/a",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "deploy": "gatsby build --prefix-paths && gh-pages -d public",
    "serve": "gatsby serve",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "gh-pages": "^1.1.0",
    "prettier": "^1.8.2"
  }
}

gatsby-node.js:

const path = require('path')

exports.createPages = ({graphql, actions}) => {
    const {createPage} = actions
    return new Promise((resolve, reject) => {
        const PortfolioPostTemplate = path.resolve('src/templates/portfolio-post.js')
        resolve(
            graphql(`
                {
                    allContentfulPortfolio (limit:100) {
                        edges {
                            node {
                                id
                                slug
                            }
                        }
                    }
                }
            `).then((result) => {
                if (result.errors) {
                    reject(result.errors)
                }
                result.data.allContentfulPortfolio.edges.forEach((edge) => {
                    createPage ({
                        path: edge.node.slug,
                        component: PortfolioPostTemplate,
                        context: {
                            slug: edge.node.slug
                        }
                    })
                })
                return
            })
        )
    })
}

gatsby-browser.js:

require('typeface-karla')

gatsby-ssr.js: N/A

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 7
  • Comments: 17 (7 by maintainers)

Commits related to this issue

Most upvoted comments

I can reproduce. The problem is not with plugin-sass but with gatsby itself.

The problem is related with the Layout component. Or rather with how gatsby tries to create html files for preloading.

Since in Header, there are 3 unique Link elements, each having its own Layout and the same css file. Gatsby for some reason embeds the same style 3 times.

By removing unique Link tags, you can notice that the number of repeated styles decreases.

https://github.com/imshuffling/davidrich.es/blob/bfb313f9ea84042bea2c6357e0fdf54a3f58d230/src/components/header.js#L7-L9

Ok, so I have found a temporal approach that works for my case, it’s not ideal but I’ll explain it here anyway in case it helps someone else with the same problem and a similar project structure.

Context/Problem: I’m working on a blog that does not contain too much CSS, I’m facing an issue where there is a lot of code duplication (CSS) when prefetching other sections of the blog, this is causing multiple inconsistencies in the site:

  • Styles being duplicated (like in the example provided by @imshuffling )
  • Unnecessary prefetching requests happening on pages that do not require new CSS.
  • Layout inconsistencies caused by the prefetch generated <Link rel ... /> tags that contain duplicated code.

In my case, as I said, the blog does not contain too much CSS so I thought that having a single file main.scss and putting it in the layout component would stop the duplicated CSS code but… it didn’t.

Solution: Instead of importing my main.scss in the layout component I ended up using the gatsby-browser.js file, which is recommended for loading global styles in some cases, by using this approach the prefetching of styles stopped happening which makes sense because we don’t have any dynamic CSS being loaded anymore…

I just added this line to my gatsby-browser.js and removed it from the layout component:

import "./src/components/main.scss"

Note: I’ll still try to dig in a little more in how gatsby constructs the CSS to see if I can be able to use CSS modules with SASS without having the code duplication between the sections, it wont be a priority in my daily tasks, but in the meantime I hope that this helps someone.

Happening to me as well on V2, when preloading by hovering a link with different layout I’m getting duplicated code that overwrites the one on my current page.

Happening to me with gatsby-plugin-sass and only in one page for now, wil keep you updated if I get to solve it.

Update 1 (no success yet): I’ve implemented multiple pages in my blog and the code keeps being repeated, I have changed the approach to use CSS modules with gatsby-plugin-sass but statements repetitions keeps happening, when debugging to try to solve it I saw it’s related with the layout component as @azdanov mentioned, if I take it out of the component then the code is not repeated for that particular link when prefetching (hovering on it).

I have also tried putting all the CSS in one main file and importing it in the layout component, I thought that maybe in this way the prefetch wouldn’t trigger because everything is imported in one file (the layout) and in fact all the links except one are not prefetching, but the link that triggers the prefetching is duplicating the whole code from the main.css so I end up having the CSS of the page inlined and in a <link rel ...> because of the prefetch of that link which lets us in the same spot we started.

Ah yeah so it is a bug. Hope this can be fixed! Maybe just check the hashes to see if they’re the same file contents?

This has probably been solved by #11800, I think it stems from the same issue.

But it’s a workaround for an actual bug, I don’t think this should be closed. If that’s a recommendation from Gatsby team, I think it’s best if the starter and docs are also updated to use gatsby-browser.js instead.

I guess code-splitting and SSR are really tricky for CSS files. 😕 Probably because importing a CSS file has an immediate side-effect of injecting it into the document, so hovering over the link actually injects the stylesheet.

<Link> is recommended because it starts loading the content on hover, it has a noticeable performance benefit. Fortunately not using it is fine too and gets rid of this CSS issue.