next.js icon indicating copy to clipboard operation
next.js copied to clipboard

styled-component overridden on hot reload

Open ghost opened this issue 8 years ago • 33 comments

  • [x ] I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior

My page contains this very basic code:

import React from 'react'
import styled from 'styled-components'

const Title = styled.h1`
  color: pink;
  font-size: 50px;
`

export default () => <Title>My page</Title>

When I refresh the page, I expect the Title to be of color pink

Current Behavior

The first time the page is built, the title does appear as pink. When I refresh the page, the pink color is no longer respected. If I change the color in the code to anything else, and save the file, then the page will update. But again, upon refreshing, the changes are lost again. I have no clue what might be causing this. Any help is appreciated.

Your Environment

Tech Version
next latest
node
OS arch
browser vivaldi

ghost avatar Mar 28 '18 02:03 ghost

I have the same bug, with a different setup. I have a monorepo with two folders :

  • app, with my next.js app
  • ui , with my 'ui library' using styled-components

I have it in an example repo : https://github.com/lucleray/ssr-ui-library

When I update the background color for example, in the ui folder, and save the file, the page updates. But then, if I refresh the page, the updates are lost.

lucleray avatar Apr 03 '18 18:04 lucleray

Is this anything to do with the injection order of the style sheets in <head>?

ianregister avatar Apr 08 '18 21:04 ianregister

@ianregister No, the order of the injection in <head> is not related

The problem is that the server and the client don't render the same code for stylesheets

lucleray avatar Apr 08 '18 21:04 lucleray

I have the same bug and it is not only on styles. Hot reload will pick up the changes, but refreshing browser does not. I have to run server again (node server.js) in order to pick up the latest update. I am using [email protected], react 16.3 and express for the server.

sea129 avatar Apr 17 '18 04:04 sea129

@lucleray, try this:

Make sure you have babel-plugin-styled-components as a dependency and in your package.json tell babel that you are doing server-side rendering.

Think that this is just a configuration issue you are facing.

package.json

"babel": {
    "env": {
      "development": {
        "presets": ["next/babel"],
        "plugins": [
          [
            "styled-components",
            {
              "ssr": true,
              "displayName": true
            }
          ]
        ]
      },
      "production": {
        "presets": ["next/babel"],
        "plugins": [
          [
            "styled-components",
            {
              "ssr": true,
              "displayName": false
            }
          ]
        ]
      }
    }
  }

tvthatsme avatar Apr 18 '18 07:04 tvthatsme

@tvthatsme I added babel-plugin-styled-components in both the ui library and the app itself, but I still have the same issue.

You can check here : https://github.com/lucleray/ssr-ui-library/blob/master/app/.babelrc https://github.com/lucleray/ssr-ui-library/blob/master/ui/.babelrc

I'm not sure it is configuration (webpack configuration), or a bug somewhere.

lucleray avatar Apr 18 '18 12:04 lucleray

having similar issue where any edits to a component (non styles related) will cause an error "Warning: Prop className did not match. Server:" on subsequent hard page fresh. Need to restart server for it to go away.

@sea129 were you able to fix?

valeeum avatar Jul 25 '18 00:07 valeeum

Lol, having the same issue here. @valeeum were you able to solve it?

chenshuiluke avatar Aug 11 '18 01:08 chenshuiluke

I did a bit of research on this issue, and I think it might be link some sort of "webpack caching".

I use the code here as an example of the issue : https://github.com/lucleray/ssr-ui-library

The app is using Next.js and has a dependency on the ui. I'm using yarn's workspace to link them but it could be a more simple yarn link.

On the server-side, the bundle does not include the ui module and treats it as external (because it's in node_modules). On the client-side, the bundle includes the ui module.

It appears like this in the .next/static (client-side) bundles :

/***/ "../ui/bundle.js":
/*!***********************!*\
  !*** ../ui/bundle.js ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, '__esModule', { value: true });

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var styled = _interopDefault(__webpack_require__(/*! styled-components */ "../node_modules/styled-components/dist/styled-components.browser.esm.js"));

const UiButton = styled.button`
  background: black;
`;

exports.UiButton = UiButton;


/***/ }),

On the other hand, in the .next/server (server-side) bundles, it appears like this :

/***/ "@monorepo/ui":
/*!*******************************!*\
  !*** external "@monorepo/ui" ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@monorepo/ui");

/***/ }),

What is weird is that module.exports = require("@monorepo/ui") should resolve to the ui package and just work fine. But it seems like it's cached and does not resolve to the actual ui package.

If I change the background color of the button in the ui to blue for example. The hot reloader updates the page correctly. But if I refresh, then the page is rendered server-side with the old color (green in my example). It's like the server-side bundle is not resolving the @monorepo/ui dependency to go the actual package, but is using a cached version of it.


It solved it by configuring webpack to treat @monorepo/ui not as an external dependency and bundle it in the server-side bundles, like this : https://github.com/lucleray/ssr-ui-library/blob/webpack-config/app/next.config.js

I would still like to understand what's happening 🤔

lucleray avatar Aug 19 '18 10:08 lucleray

require has a built-in cache (require.cache) this is expected behavior for dependencies in node_modules, as we won't bundle anything inside node_modules on the server (for compilation speed).

timneutkens avatar Aug 19 '18 13:08 timneutkens

Ok, that makes sense.

So the issue is that the hot-reloader doesn't reload the code changes in external dependencies, on the server-side, right ?

In the example I shared, I expect my code changes to be loaded both on client (which is the case) and server (which is not the case) side in development mode.

lucleray avatar Aug 19 '18 22:08 lucleray

So the issue is that the hot-reloader doesn't reload the code changes in external dependencies, on the server-side, right?

Exactly, we only delete full paths from the require.cache.

timneutkens avatar Aug 20 '18 06:08 timneutkens

How do you think I could solve this @timneutkens ?

Should I remove @monorepo/ui from the external dependencies so it's bundled in the server-side bundles ? That works but since I'm already transpiling it, wouldn't it better to just require it ?

lucleray avatar Aug 20 '18 22:08 lucleray

It might be as easy as using https://github.com/martpie/next-plugin-transpile-modules to enable module compilation.

timneutkens avatar Nov 08 '18 12:11 timneutkens

@timneutkens Why was this closed? this issue still exists on the latest version

jeankvd avatar Mar 15 '19 00:03 jeankvd

Still having this issue as well

oscargws avatar Apr 06 '19 13:04 oscargws

Im still having this issue too

alesoto13 avatar Apr 08 '19 20:04 alesoto13

Ditto too here

Ruegen avatar Apr 14 '19 01:04 Ruegen

Also having this issue

Edit (solution):

This issue is related to not having the babel config setup correctly. If you look at the official example of NextJS with styled-components you'll notice they have a .babelrc file with:

{
    "presets": ["next/babel"],
    "plugins": [["styled-components", { "ssr": true }]]
}

Then you must add this plugin to the devDependencies in your package.json file

"devDependencies": {
    "babel-plugin-styled-components": "^1.8.0"
},

Then run your install command, yarn install or npm install and then you'll be good to go!

P.S: Be sure to only have one tab open for your localhost dev work!

MadMaxMcKinney avatar Apr 19 '19 21:04 MadMaxMcKinney

ok people. here is the solution. create an _document.js in root of directory and add this.

import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

class MyDocument extends Document {
  static getInitialProps ({ renderPage }) {
    const sheet = new ServerStyleSheet()
    const page = renderPage(App => props => sheet.collectStyles(<App {...props} />))
    const styleTags = sheet.getStyleElement()
    return { ...page, styleTags }
  }

  render () {
    return (
      <html>
        <Head>
          <title>Your site title</title>
          {this.props.styleTags}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

export default MyDocument

then npm install --save -D babel-plugin-styled-components

also create a custom app in pages directory, _App.js and add:

import React from "react";
import App from "next/app";

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;
    return <Component {...pageProps} />;
  }
}

export default MyApp;

you're all set

ghost avatar Sep 04 '19 03:09 ghost