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

Created on 21 Aug 2018  路  17Comments  路  Source: gatsbyjs/gatsby

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(R) Core(TM) 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 <[email protected]>",
  "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

help wanted stale? bug

Most helpful comment

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

All 17 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

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?

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.

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.

Thanks @enmanuelduran - Ill check this out on my end

This cause two issues for me, one which could be fixed with better CSS architecture on my part. Firstly I also included my base CSS in a layout component, and in that, I loaded my fonts. When I hovered over a link for the first time I would see all the fonts be reloaded and the entire site flash.

I solved this by simply moving those includes into gatsby-browser.js, which is arguably a much better place for them anyway.

My second problem is when the CSS is reloaded, some components that include universal selectors get reloaded a win specificity over components in the page already. This causes the layout to break. I'm new to CSS Modules, so I think I could design my architecture better and it should solve the problem. For now I will just make sure the specificity always wins regardless of source order as a quick fix.

This fixes my layout problems but there is lots of wasted bytes tied to this.

I'm not 100% sure if the problem stems from this, but when hovering over some links, some of the CSS that is loaded is from a different file unique to that component, but the contents are identical to other page components. There's no deduping happening.

It might also be worth noting that I'm not using gatsby-plugin-sass, but I am using gatsby-plugin-postcss

I have a lot of CSS files, with the assumption that the module bundling would put them in the correct order. I don't want to have to worry about specificity, that's the point of CSS Modules.

I realized that simply using <a> instead of Gatsby's <Link> component is a good workaround until this gets resolved.

@silvenon this is what I ended up doing for now, does using have any performance benefits?

<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.

Hi! I also ran into this issue - or a very similar one - in production. While swapping Link with a fixed the prefetching dupes, Gatsby isn't common-chunking or deduping reused component styles when they're imported by multiple bundles. So, for instance -

So, assume ExampleComp has some modular class - we'll call itbase-class
1) FirstPage renders ExampleComp, adds a className with its own modular class- we'll call it override-class. As expected, override-class rules override base-class rules
2) User navigates to SecondPage
3) SecondPage also renders ExampleComp, which injects another copy of base-class
4) User navigates back to FirstPage
5) Now, ExampleComp is styled according to the cascade: base-class overrides override-class which overrides base-class. ExampleComp breaks.

I've had to fiddle quite a bit with different webpack configs to get everything lined up, but I can't seem to shake this bug. Has anyone seen anything similar?

@alexjhannan I'm seeing a very similar issue on my website. It doesn't break the functionality, but it certainly puts a hiccup in the user experience. I've been fiddling with it for most of today and can't seem to find anything. Let me know if you're able to come up with a solution, and we can go from there.

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.

Hiya!

This issue has gone quiet. Spooky quiet. 馃懟

We get a lot of issues, so we currently close issues after 30 days of inactivity. It鈥檚 been at least 20 days since the last update here.

If we missed this issue or if you want to keep it open, please reply here. You can also add the label "not stale" to keep this issue open!

Thanks for being a part of the Gatsby community! 馃挭馃挏

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

@silvenon I've just updated my site locally and there seems to be no duplication errors. Can anyone else confirm?

Closing this as #11800 solved the issue for me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

theduke picture theduke  路  3Comments

dustinhorton picture dustinhorton  路  3Comments

KyleAMathews picture KyleAMathews  路  3Comments

kalinchernev picture kalinchernev  路  3Comments

mikestopcontinues picture mikestopcontinues  路  3Comments