Gatsby: netlify-cms css inlined on every route

Created on 28 Jan 2018  Â·  20Comments  Â·  Source: gatsbyjs/gatsby

Description

I installed gatsby-plugin-netlify-cms and now have the Netlify-CMS css file inlined into the head of every page of my site. I don't know if this is expected behaviour but it seems like it would make more sense for this to only get injected on the '/admin' route.

This is especially bad because Netlify-CMS doesn't scope its styles, so e.g. my headings are getting css applied that I don't want.

Environment

Gatsby version: 1.9.172
Node.js version: 8.9.4
Operating System: macOS 10.13.2

File contents (if changed):

gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: 'Oliver James',
    author: 'Oliver Phillips',
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              // Class prefix for <pre> tags containing syntax highlighting;
              // defaults to 'language-' (eg <pre class="language-js">).
              // If your site loads Prism into the browser at runtime,
              // (eg for use with libraries like react-live),
              // you may use this to prevent Prism from re-processing syntax.
              // This is an uncommon use-case though;
              // If you're unsure, it's best to use the default value.
              classPrefix: 'language-',
            },
          },
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 590,
            },
          },
          {
            resolve: `gatsby-remark-responsive-iframe`,
            options: {
              wrapperStyle: `margin-bottom: 1.0725rem`,
            },
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants',
        ],
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    `gatsby-plugin-offline`,
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-styled-components`,
    `gatsby-plugin-netlify-cms`,
  ],
};

package.json:

{
  "name": "oliverjam",
  "description": "Personal site",
  "version": "1.0.0",
  "author": "Oliver Phillips",
  "dependencies": {
    "gatsby": "^1.9.172",
    "gatsby-link": "^1.6.35",
    "gatsby-plugin-google-analytics": "^1.0.16",
    "gatsby-plugin-manifest": "^1.0.13",
    "gatsby-plugin-netlify-cms": "^1.0.5",
    "gatsby-plugin-offline": "^1.0.13",
    "gatsby-plugin-preact": "^1.0.15",
    "gatsby-plugin-react-helmet": "^1.0.8",
    "gatsby-plugin-sharp": "^1.6.27",
    "gatsby-remark-copy-linked-files": "^1.5.25",
    "gatsby-remark-images": "^1.5.41",
    "gatsby-remark-prismjs": "^1.2.12",
    "gatsby-remark-responsive-iframe": "^1.4.16",
    "gatsby-remark-smartypants": "^1.4.10",
    "gatsby-source-filesystem": "^1.5.15",
    "gatsby-transformer-remark": "^1.7.30",
    "gatsby-transformer-sharp": "^1.6.17",
    "lodash": "^4.15.0",
    "polished": "^1.9.0",
    "recompose": "^0.26.0",
    "styled-system": "^1.1.1",
    "unfetch": "^3.0.0"
  },
  "devDependencies": {
    "gatsby-plugin-styled-components": "^1.0.5",
    "gh-pages": "^0.12.0",
    "prettier": "^1.10.2"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "main": "n/a",
  "scripts": {
    "dev": "gatsby develop",
    "lint": "./node_modules/.bin/eslint --ext .js,.jsx --ignore-pattern public .",
    "test": "echo \"Error: no test specified\" && exit 1",
    "format": "prettier --trailing-comma es5 --no-semi --single-quote --write 'src/**/*.js'",
    "develop": "gatsby develop",
    "build": "gatsby build",
    "deploy": "gatsby build --prefix-paths && gh-pages -d public",
    "fix-semi": "eslint --quiet --ignore-pattern node_modules --ignore-pattern public --parser babel-eslint --no-eslintrc --rule '{\"semi\": [2, \"never\"], \"no-extra-semi\": [2]}' --fix gatsby-node.js"
  }
}

gatsby-node.js:

const _ = require("lodash")
const Promise = require("bluebird")
const path = require("path")
const select = require(`unist-util-select`)
const fs = require(`fs-extra`)

exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators

  return new Promise((resolve, reject) => {
    const pages = []
    const blogPost = path.resolve("./src/templates/blog-post.js")
    resolve(
      graphql(
        `
      {
        allMarkdownRemark(limit: 1000) {
          edges {
            node {
              frontmatter {
                path
              }
            }
          }
        }
      }
    `
      ).then(result => {
        if (result.errors) {
          console.log(result.errors)
          reject(result.errors)
        }

        // Create blog posts pages.
        _.each(result.data.allMarkdownRemark.edges, edge => {
          createPage({
            path: edge.node.frontmatter.path,
            component: blogPost,
            context: {
              path: edge.node.frontmatter.path,
            },
          })
        })
      })
    )
  })
}

Actual result

The <head> of all my routes has the Netlify-CMS css injected into the <style id="gatsby-inlined-css"> tag.

Expected behavior

Only the '/admin' route (where Netlify-CMS lives) should have this css injected.

Steps to reproduce

1. Install gatsby-plugin-netlify-cms

2. Build your site

3. See the injected Netlify css on all pages

Most helpful comment

This seems to be an issue with any css imports. E.g. if I import some Prism syntax highlighting css in my blog template it still gets injected onto every page (even though the js itself is code-split).

I got around this by putting all my css into Styled-Components so it's just part of the bundle, but that's not really a solution if a plugin is importing it.

All 20 comments

/cc @erquhart

Yep, I have noticed this too. I just removed the import to the css file in the src/cms/cms.js file.

This seems to be an issue with any css imports. E.g. if I import some Prism syntax highlighting css in my blog template it still gets injected onto every page (even though the js itself is code-split).

I got around this by putting all my css into Styled-Components so it's just part of the bundle, but that's not really a solution if a plugin is importing it.

I'll dig into this soon.

@oliverjam hmm I'm unable to repro. The Gatsby Netlify CMS starter demo doesn't do it, and I even cloned your repo, went back to the commit before you commented out the Netlify CMS plugin, and tested that with both dev and production builds - no Netlify CMS styles outside of the /admin/ path.

Can you provide a repro case?

This is very strange but I can't reproduce either now... I have no idea what was going on before, but I definitely had a load of Netlify-CMS CSS in a style tag in the head of every page.

Strangely my Gatsby-inlined CSS also no longer has the "gatsby-inlined-css" ID.

Thanks for looking into this, and sorry for wasting your time! I'll re-open the issue if this re-emerges at some point :)

Okay I managed to reproduce it. It's only happening when I build—running the dev server doesn't output the CSS for some reason. You can see it live at https://oliverjam.es right now as I've left it deployed broken. Here's a screenshot:

screen shot 2018-02-04 at 23 48 57

Any ideas why that's happening?

Edit: Just for reference here's the commit where I re-enabled the Netlify-CMS plugin.

I see in your repo that supplying your own cms.js fixed it. Need to figure out the difference between how webpack handles these two cases - should be a separate chunk either way, but there's leakage somewhere.

@erquhart I thought that had fixed it but actually once it built and deployed the problem was still there. The plugin seems to leak the css no matter what I do, so I've removed it for now

Figured it out, two issues:

  1. The Netlify CMS plugin needs to exclude it's own CSS from the build-css phase and not just build-javascript. PR forthcoming for that.
  2. In it's current form, the Purify CSS plugin can't be used with Netlify CMS (and perhaps others) due to it accessing files apart from webpack (so it doesn't know about entry points, chunks, etc - it processes every css file in the public directory). The author of that plugin may have suggestions on how to workaround, opened https://github.com/rongierlach/gatsby-plugin-purify-css/issues/5 on that repo.

So as soon as my PR gets merged and released, your site will work as long as the Purify CSS plugin is removed.

@erquhart thank you for bringing to my attention.
Looking into this on https://github.com/rongierlach/gatsby-plugin-purify-css/issues/5

@erquhart That's amazing, thanks so much for looking into it!

Is this fixed and released? when i run yarn build on my local machine (win10) public/index.html still contains a bunch of unrelated css. you can have a look at this test-repo.

@PutziSan I cloned your repo and built it, no CSS in the output:

<!DOCTYPE html>
<html>

<head>
    <meta charSet="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <link rel="preload" href="/component---src-pages-index-jsx-8b3e6fdfcc0473aa142e.js" as="script" />
    <link rel="preload" href="/path---index-a0e39f21c11f6a62c5ab.js" as="script" />
    <link rel="preload" href="/app-4eb7cf0abaf5dc714e3a.js" as="script" />
    <link rel="preload" href="/commons-611c88095698110795da.js" as="script" />
    <style id="gatsby-inlined-css"></style>
</head>

<body>
    <div id="___gatsby">
        <div data-reactroot="">
            <div>
                <h1>Hello world!</h1><a href="/test-entry">Link to /test-entry</a><a href="/test-with-image">Link to /test-entry</a></div>
        </div>
    </div>
    <script id="webpack-manifest">
        /*<![CDATA[*/
        window.webpackManifest = {
            "231608221292675": "app-4eb7cf0abaf5dc714e3a.js",
            "45382528579085": "component---src-templates-blog-template-jsx-d4e9abe12f03fba3aee6.js",
            "213534597649335": "component---src-pages-index-jsx-8b3e6fdfcc0473aa142e.js",
            "39906862311260": "path---test-with-image-134f05fab08c413752c2.js",
            "43212999683444": "path---test-entry-1ed238a266786e21ac66.js",
            "142629428675168": "path---index-a0e39f21c11f6a62c5ab.js"
        } /*]]>*/
    </script>
    <script>
        /*<![CDATA[*/ ! function(e, t, r) {
            function n() {
                for (; d[0] && "loaded" == d[0][f];) c = d.shift(), c[o] = !i.parentNode.insertBefore(c, i)
            }
            for (var s, a, c, d = [], i = e.scripts[0], o = "onreadystatechange", f = "readyState"; s = r.shift();) a = e.createElement(t), "async" in i ? (a.async = !1, e.head.appendChild(a)) : i[f] ? (d.push(a), a[o] = n) : e.write("<" + t + ' src="' + s + '" defer></' + t + ">"), a.src = s
        }(document, "script", ["/commons-611c88095698110795da.js", "/app-4eb7cf0abaf5dc714e3a.js", "/path---index-a0e39f21c11f6a62c5ab.js", "/component---src-pages-index-jsx-8b3e6fdfcc0473aa142e.js"]) /*]]>*/
    </script>
</body>

</html>

I updated my project: removed the public-dir from .gitignore and added a fresh build via yarn run build, you can see the output here (html-file is not beautified).

The CSS-stuff is injected, but i can confirm when netlify run the build-step, there is no css in the output.

the beautified version of the html (style is collapsed, notice the line-numbers, more than 2k lines css-code

image

screenshot from my build-script:

image

It sounds like you're saying that this bug is only happening when you build locally, and I see you're on Windows. Netlify is building your site on Linux, I'm building your site locally with a Mac, and the bug isn't happening in those two cases. This may be a Windows specific issue somehow.

Yeah, it seems to be the case. Can someone else confirm the problem (possibly only on windows)?

Should I then open a new issue for this or is this here enough?

I'd open a new issue.

Sent with GitHawk

@PutziSan happening here on Windows builds as well.

Ok, so this is interesting.

Importing a typeface from KyleAMathews/typefaces seems to have "fixed it". Instead of the netlify-cms css being injected on every page via gatsby-inline-css, the font I imported is injected.

Why this is happening is beyond me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

totsteps picture totsteps  Â·  3Comments

kalinchernev picture kalinchernev  Â·  3Comments

dustinhorton picture dustinhorton  Â·  3Comments

rossPatton picture rossPatton  Â·  3Comments

ghost picture ghost  Â·  3Comments