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

Server-side-rendered styles differ from the ones used during development #3741

Closed
kripod opened this issue Jan 27, 2018 · 12 comments
Closed

Comments

@kripod
Copy link
Contributor

kripod commented Jan 27, 2018

Description

When I import normalize.css and then use the injectGlobal function of react-emotion, then I get inconsistent results between development and production builds.

Environment

Gatsby version: 1.9.165
Node.js version: 8.9.3
Operating System: Windows 10 x64

File contents (if changed):

gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: 'Not relevant',
  },
  mapping: {
    'MarkdownRemark.frontmatter.society': 'SocietiesYaml',
  },
  plugins: [
    'gatsby-plugin-emotion',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'data',
        path: `${__dirname}/data/`,
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'static',
        path: `${__dirname}/static/`,
      },
    },
    'gatsby-transformer-remark',
    'gatsby-transformer-yaml',
  ],
};

pages/index.jsx:

import React from 'react';
import { injectGlobal } from 'react-emotion';

import 'normalize.css';

injectGlobal`
  fieldset {
    padding: 0; // The effect of this gets overrided by https://github.com/necolas/normalize.css/blob/73b6b0c7e8690ab5005bca9d7e13d3fb319c98ac/normalize.css#L311-L313
  }
`;

const IndexPage = () => (
  <fieldset>
    <legend>Title</legend>
    <input type="radio" id="radio">
    <label for="radio">Click me</label>
  </fieldset>
);

export default IndexPage;

Actual result

In production mode, the styles defined in the injectGlobal method are overrided by the styles of normalize.css. (Development mode works as expected.)

Expected behavior

The injection of styles should always happen in the order of their definition.

@KyleAMathews
Copy link
Contributor

The order of server rendered styles are determined by how you add styles to your html.js. This is a tricky issue since in development, styles are added by JS in the client, and in SSR, they're added by plugins / either the default or your custom html.js component.

There's not a simple way to solve this.

Ideally you use only one technology for injecting CSS e.g. use emotion as well to inject the normalize.css file.

@kripod
Copy link
Contributor Author

kripod commented Jan 27, 2018

Actually, I just tried switching to emotion-only injects by using the following code inside gatsby-node.js:

exports.modifyWebpackConfig = ({ config, stage }) => {
  if (stage === 'develop' || stage === 'build-css') {
    config.loader('css', current => ({
      ...current,
      loader: 'raw',
    }));
  }

  return config;
};

Now, normalize.css doesn't even get added to the bundle during production build.

@kripod
Copy link
Contributor Author

kripod commented Jan 27, 2018

@KyleAMathews I tried to tweak my gatsby-node.js even further and finally got the order right, but now, the contents of normalize.css don't get SSR'ed as CSS, but as JS.

gatsby-node.js:

exports.modifyWebpackConfig = ({ config, stage }) => {
  if (stage === 'develop' || stage === 'build-javascript') {
    // Load only the raw contents of regular CSS files to support CSS-in-JS
    config.loader('css', ({ loaders, ...current }) => ({
      ...current,
      loader: 'raw',
    }));
  } else if (stage === 'build-css') {
    // Regular CSS files shall not be processed in this stage anymore
    config.loader('css', ({ loaders, ...current }) => ({
      ...current,
      loader: 'null',
    }));
  }

  return config;
};

pages/index.jsx:

import { injectGlobal } from 'react-emotion';

import normalizeCSS from 'normalize.css';

injectGlobal`${normalizeCSS}`;
console.log(normalizeCSS); // Works fine during development and production

injectGlobal`
  body {
    box-sizing: border-box;
    font-family: Montserrat, sans-serif;
    overflow-x: hidden;
  }

  /* ... */
`;

I would appreciate if you could explain what I'm not taking into consideration...

@KyleAMathews
Copy link
Contributor

Import the css like this:

import normalizeCSS from 'raw-loader!normalize.css';

That way you'll stop also loading the CSS through the normal css loader.

@kripod
Copy link
Contributor Author

kripod commented Jan 27, 2018

@KyleAMathews Unfortunately, that doesn't work because it sets normalizeCSS to the following string:

module.exports = "/*! normalize.css v7.0.0 | MIT License | github.com/necolas/normalize.css */\n\n/* Document\n   ========================================================================== */\n\n/**\n * 1. Correct the line height in all browsers.\n * 2. Prevent adjustments of font size after orientation changes in\n *    IE on Windows Phone and in iOS.\n */\n\nhtml {\n  line-height: 1.15; /* 1 */\n  -ms-text-size-adjust: 100%; /* 2 */\n  -webkit-text-size-adjust: 100%; /* 2 */\n}\n\n/* Sections\n   ========================================================================== */\n\n/**\n * Remove the margin in all browsers (opinionated).\n */\n\nbody {\n  margin: 0;\n}\n\n/**\n * Add the correct display in IE 9-.\n */\n\narticle,\naside,\nfooter,\nheader,\nnav,\nsection {\n  display: block;\n}\n\n/**\n * Correct the font size and margin on `h1` elements within `section` and\n * `article` contexts in Chrome, Firefox, and Safari.\n */\n\nh1 {\n  font-size: 2em;\n  margin: 0.67em 0;\n}\n\n/* Grouping content\n   ========================================================================== */\n\n/**\n * Add the correct display in IE 9-.\n * 1. Add the correct display in IE.\n */\n\nfigcaption,\nfigure,\nmain { /* 1 */\n  display: block;\n}\n\n/**\n * Add the correct margin in IE 8.\n */\n\nfigure {\n  margin: 1em 40px;\n}\n\n/**\n * 1. Add the correct box sizing in Firefox.\n * 2. Show the overflow in Edge and IE.\n */\n\nhr {\n  box-sizing: content-box; /* 1 */\n  height: 0; /* 1 */\n  overflow: visible; /* 2 */\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\npre {\n  font-family: monospace, monospace; /* 1 */\n  font-size: 1em; /* 2 */\n}\n\n/* Text-level semantics\n   ========================================================================== */\n\n/**\n * 1. Remove the gray background on active links in IE 10.\n * 2. Remove gaps in links underline in iOS 8+ and Safari 8+.\n */\n\na {\n  background-color: transparent; /* 1 */\n  -webkit-text-decoration-skip: objects; /* 2 */\n}\n\n/**\n * 1. Remove the bottom border in Chrome 57- and Firefox 39-.\n * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.\n */\n\nabbr[title] {\n  border-bottom: none; /* 1 */\n  text-decoration: underline; /* 2 */\n  text-decoration: underline dotted; /* 2 */\n}\n\n/**\n * Prevent the duplicate application of `bolder` by the next rule in Safari 6.\n */\n\nb,\nstrong {\n  font-weight: inherit;\n}\n\n/**\n * Add the correct font weight in Chrome, Edge, and Safari.\n */\n\nb,\nstrong {\n  font-weight: bolder;\n}\n\n/**\n * 1. Correct the inheritance and scaling of font size in all browsers.\n * 2. Correct the odd `em` font sizing in all browsers.\n */\n\ncode,\nkbd,\nsamp {\n  font-family: monospace, monospace; /* 1 */\n  font-size: 1em; /* 2 */\n}\n\n/**\n * Add the correct font style in Android 4.3-.\n */\n\ndfn {\n  font-style: italic;\n}\n\n/**\n * Add the correct background and color in IE 9-.\n */\n\nmark {\n  background-color: #ff0;\n  color: #000;\n}\n\n/**\n * Add the correct font size in all browsers.\n */\n\nsmall {\n  font-size: 80%;\n}\n\n/**\n * Prevent `sub` and `sup` elements from affecting the line height in\n * all browsers.\n */\n\nsub,\nsup {\n  font-size: 75%;\n  line-height: 0;\n  position: relative;\n  vertical-align: baseline;\n}\n\nsub {\n  bottom: -0.25em;\n}\n\nsup {\n  top: -0.5em;\n}\n\n/* Embedded content\n   ========================================================================== */\n\n/**\n * Add the correct display in IE 9-.\n */\n\naudio,\nvideo {\n  display: inline-block;\n}\n\n/**\n * Add the correct display in iOS 4-7.\n */\n\naudio:not([controls]) {\n  display: none;\n  height: 0;\n}\n\n/**\n * Remove the border on images inside links in IE 10-.\n */\n\nimg {\n  border-style: none;\n}\n\n/**\n * Hide the overflow in IE.\n */\n\nsvg:not(:root) {\n  overflow: hidden;\n}\n\n/* Forms\n   ========================================================================== */\n\n/**\n * 1. Change the font styles in all browsers (opinionated).\n * 2. Remove the margin in Firefox and Safari.\n */\n\nbutton,\ninput,\noptgroup,\nselect,\ntextarea {\n  font-family: sans-serif; /* 1 */\n  font-size: 100%; /* 1 */\n  line-height: 1.15; /* 1 */\n  margin: 0; /* 2 */\n}\n\n/**\n * Show the overflow in IE.\n * 1. Show the overflow in Edge.\n */\n\nbutton,\ninput { /* 1 */\n  overflow: visible;\n}\n\n/**\n * Remove the inheritance of text transform in Edge, Firefox, and IE.\n * 1. Remove the inheritance of text transform in Firefox.\n */\n\nbutton,\nselect { /* 1 */\n  text-transform: none;\n}\n\n/**\n * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`\n *    controls in Android 4.\n * 2. Correct the inability to style clickable types in iOS and Safari.\n */\n\nbutton,\nhtml [type=\"button\"], /* 1 */\n[type=\"reset\"],\n[type=\"submit\"] {\n  -webkit-appearance: button; /* 2 */\n}\n\n/**\n * Remove the inner border and padding in Firefox.\n */\n\nbutton::-moz-focus-inner,\n[type=\"button\"]::-moz-focus-inner,\n[type=\"reset\"]::-moz-focus-inner,\n[type=\"submit\"]::-moz-focus-inner {\n  border-style: none;\n  padding: 0;\n}\n\n/**\n * Restore the focus styles unset by the previous rule.\n */\n\nbutton:-moz-focusring,\n[type=\"button\"]:-moz-focusring,\n[type=\"reset\"]:-moz-focusring,\n[type=\"submit\"]:-moz-focusring {\n  outline: 1px dotted ButtonText;\n}\n\n/**\n * Correct the padding in Firefox.\n */\n\nfieldset {\n  padding: 0.35em 0.75em 0.625em;\n}\n\n/**\n * 1. Correct the text wrapping in Edge and IE.\n * 2. Correct the color inheritance from `fieldset` elements in IE.\n * 3. Remove the padding so developers are not caught out when they zero out\n *    `fieldset` elements in all browsers.\n */\n\nlegend {\n  box-sizing: border-box; /* 1 */\n  color: inherit; /* 2 */\n  display: table; /* 1 */\n  max-width: 100%; /* 1 */\n  padding: 0; /* 3 */\n  white-space: normal; /* 1 */\n}\n\n/**\n * 1. Add the correct display in IE 9-.\n * 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.\n */\n\nprogress {\n  display: inline-block; /* 1 */\n  vertical-align: baseline; /* 2 */\n}\n\n/**\n * Remove the default vertical scrollbar in IE.\n */\n\ntextarea {\n  overflow: auto;\n}\n\n/**\n * 1. Add the correct box sizing in IE 10-.\n * 2. Remove the padding in IE 10-.\n */\n\n[type=\"checkbox\"],\n[type=\"radio\"] {\n  box-sizing: border-box; /* 1 */\n  padding: 0; /* 2 */\n}\n\n/**\n * Correct the cursor style of increment and decrement buttons in Chrome.\n */\n\n[type=\"number\"]::-webkit-inner-spin-button,\n[type=\"number\"]::-webkit-outer-spin-button {\n  height: auto;\n}\n\n/**\n * 1. Correct the odd appearance in Chrome and Safari.\n * 2. Correct the outline style in Safari.\n */\n\n[type=\"search\"] {\n  -webkit-appearance: textfield; /* 1 */\n  outline-offset: -2px; /* 2 */\n}\n\n/**\n * Remove the inner padding and cancel buttons in Chrome and Safari on macOS.\n */\n\n[type=\"search\"]::-webkit-search-cancel-button,\n[type=\"search\"]::-webkit-search-decoration {\n  -webkit-appearance: none;\n}\n\n/**\n * 1. Correct the inability to style clickable types in iOS and Safari.\n * 2. Change font properties to `inherit` in Safari.\n */\n\n::-webkit-file-upload-button {\n  -webkit-appearance: button; /* 1 */\n  font: inherit; /* 2 */\n}\n\n/* Interactive\n   ========================================================================== */\n\n/*\n * Add the correct display in IE 9-.\n * 1. Add the correct display in Edge, IE, and Firefox.\n */\n\ndetails, /* 1 */\nmenu {\n  display: block;\n}\n\n/*\n * Add the correct display in all browsers.\n */\n\nsummary {\n  display: list-item;\n}\n\n/* Scripting\n   ========================================================================== */\n\n/**\n * Add the correct display in IE 9-.\n */\n\ncanvas {\n  display: inline-block;\n}\n\n/**\n * Add the correct display in IE.\n */\n\ntemplate {\n  display: none;\n}\n\n/* Hidden\n   ========================================================================== */\n\n/**\n * Add the correct display in IE 10-.\n */\n\n[hidden] {\n  display: none;\n}\n"

I don't want it to be converted to a file with module.exports.

@KyleAMathews
Copy link
Contributor

@kripod probably need to import an actual css file then

@KyleAMathews
Copy link
Contributor

or there's something goofy with our raw loader setup because it should just give you the actual text of the file.

@kripod
Copy link
Contributor Author

kripod commented Jan 27, 2018

@KyleAMathews It seems that the normalize.css package exports an actual CSS file. Even by using import normalizeCSS from 'raw-loader!normalize.css/normalize.css';, I get the same results, so there may be something goofy with the raw loader setup of Gatsby.

@KyleAMathews
Copy link
Contributor

Oh my bad. You need to add an exclamation mark as well at the start to disable the normal loader chain.

I just tested this in a new project and it imported the raw css string as expected:

import React from "react"
import normalizeCSS from "!raw-loader!normalize.css"
console.log(normalizeCSS)

export default () => <div>Hello world!</div>

@kripod
Copy link
Contributor Author

kripod commented Jan 27, 2018

@KyleAMathews Awesome, and I don't even need a gatsby-node.js, then. Thank you so much! 😊

@skube
Copy link
Contributor

skube commented May 9, 2018

While this works for me, I do get an eslint error:

[eslint] Unexpected '!' in '!raw-loader!normalize.css'.
Do not use import syntax to configure webpack loaders.
(import/no-webpack-loader-syntax)

@blainekasten
Copy link
Contributor

#25729

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants