Cully
Cully

Reputation: 6975

Using styled-jsx with postcss, styles not reloading/rebuilding

I'm using postcss with styled-jsx. I have a few CSS files that I'm including using @import in _app.js. This works just fine, except when I make changes to the CSS files, Next.js doesn't rebuild the app. I kinda get that since it's likely not watching CSS files for changes. However, I can't do anything to make Next.js rebuild with the changes. I've tried changing and saving _app.js. I get a rebuild, but the changes aren't included. I can delete the .next folder and that works. Here's what my includes look like:

export default const App = ({Component, pageProps}) => {
  return (
    <>
      <Component {...pageProps} />

      <style jsx global>
        {`
          @import '@css/variables.css';
          @import '@css/mixins.css';
          @import '@css/reset.css';
          @import '@css/body.css';
          @import '@css/grid.css';
          @import '@css/form.css';
        `}
      </style>
    </>
  )
}

Any idea what might be going wrong?

Upvotes: 1

Views: 545

Answers (2)

Cully
Cully

Reputation: 6975

I ended up resolving this by going a different route; probably the best-practice in this situation. I'll post my solution in case it's helpful.

I just used next-css (see update at the bottom of the post), and a javscript import to include the files. I'll post code below. I found a couple benefits to this way of doing it:

  1. Next.js automatically catches changes and rebuilds.
  2. Sourcemaps work better. Before, when I clicked on the source of a style in dev tools, it would just point me to my <style>@import... statement. Not helpful. EDIT: Actually, sourcemap seems to be broken for me. Something to do with postcss and next-css not playing well together, I think.

In the end, this is probably a better way to do it. Though, I'd still like to know if there's a resolution that works with what I posted originally.

_app.js

@import 'path/to/global.css'

export default const App = ({Component, pageProps}) => {
  return (
    <Component {...pageProps} />
  )
};

To forestall questions, there is more to this file than I'm showing. Really just including it to show the difference between my original post and the solution.

global.css

@import '@css/variables.css';
@import '@css/mixins.css';
@import '@css/reset.css';
@import '@css/body.css';
@import '@css/grid.css';
@import '@css/form.css';

next.config.js

const withCSS = require('@zeit/next-css')

module.exports = withCSS({})

UPDATE (01/26/20): Next.js 9.2 now has built-in support for importing CSS files. So you can get rid of the next-css stuff. Plus it fixes sourcemaps; so that works great.

Upvotes: 0

Elyas Pourmotazedy
Elyas Pourmotazedy

Reputation: 732

add empty style in _app.js like this

import 'nameofyourfile.css'

Upvotes: 0

Related Questions