Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v2] gatsby - Duplicate styles when serving site #7517

Closed
imshuffling opened this issue Aug 21, 2018 · 17 comments
Closed

[v2] gatsby - Duplicate styles when serving site #7517

imshuffling opened this issue Aug 21, 2018 · 17 comments
Labels
help wanted Issue with a clear description that the community can help with. stale? Issue that may be closed soon due to the original author not responding any more. type: bug An issue or pull request relating to a bug in Gatsby

Comments

@imshuffling
Copy link
Contributor

imshuffling commented Aug 21, 2018

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

@azdanov
Copy link
Contributor

azdanov commented Aug 21, 2018

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

@azdanov azdanov added the type: bug An issue or pull request relating to a bug in Gatsby label Aug 21, 2018
@azdanov azdanov changed the title [v2] gatsby-plugin-sass - Duplicate styles when serving site [v2] gatsby - Duplicate styles when serving site Aug 21, 2018
@outofthisworld
Copy link
Contributor

outofthisworld commented Aug 31, 2018

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?

@azdanov azdanov added the help wanted Issue with a clear description that the community can help with. label Aug 31, 2018
@enmanuelduran
Copy link

enmanuelduran commented Sep 19, 2018

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.

@enmanuelduran
Copy link

enmanuelduran commented Sep 23, 2018

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.

@imshuffling
Copy link
Contributor Author

Thanks @enmanuelduran - Ill check this out on my end

@simonlc
Copy link

simonlc commented Oct 12, 2018

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

@silvenon
Copy link

silvenon commented Oct 17, 2018

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 added a commit to silvenon/silvenon.com that referenced this issue Oct 17, 2018
The CSS in production doesn't behave the same as in development. The
main problem is that hovering over links appends CSS from that route,
but that CSS is already included and it messes up the specificity.

The only workaround that I know of is avoiding Gatsby's Link component
until that issue gets resolved. Too bad, prefetching was pretty cool.

gatsbyjs/gatsby#7517
@imshuffling
Copy link
Contributor Author

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

@silvenon
Copy link

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

@dassidas
Copy link

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?

@ckreiling
Copy link

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

@imshuffling
Copy link
Contributor Author

I resolved it using #7517 (comment)

@silvenon
Copy link

silvenon commented Jan 31, 2019

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.

@imshuffling imshuffling reopened this Feb 4, 2019
@gatsbot
Copy link

gatsbot bot commented Feb 25, 2019

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’s 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! 💪💜

@gatsbot gatsbot bot added the stale? Issue that may be closed soon due to the original author not responding any more. label Feb 25, 2019
@silvenon
Copy link

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

@imshuffling
Copy link
Contributor Author

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

@imshuffling
Copy link
Contributor Author

Closing this as #11800 solved the issue for me.

silvenon added a commit to silvenon/silvenon.com that referenced this issue May 21, 2019
Now Gatsby no longer has issues with duplicating styles when preloading.

gatsbyjs/gatsby#7517
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Issue with a clear description that the community can help with. stale? Issue that may be closed soon due to the original author not responding any more. type: bug An issue or pull request relating to a bug in Gatsby
Projects
None yet
Development

No branches or pull requests

8 participants