Nasir Altaf
Nasir Altaf

Reputation: 47

How to get global styles inside in a <style> tag after running the build in NextJS?

I have a problem with my NextJS project. When I run 'yarn dev' I get the global styles inside a <style> tag, where I need them to be for page performance and to stop Layout Shift from occurring when the page loads. But when I run 'yarn build' followed by 'yarn start' the global styles end up in a <link rel='stylesheet' href... /> tag. Hence my issue. Here is my code:

_app.js

import Layout from '../components/Layout'
import '../styles/globals.css'
import '../styles/header.scss'
import '../styles/nav.scss'

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

export default MyApp

Packages installed

├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

I've been reading around and found mention of 'next.config.js'. I don't have a config file like this in my project at the moment... is this something I need or is there something else I'm missing?

My first time using both React and NextJS so any help would be massively appreciated. Thanks

Upvotes: 0

Views: 4899

Answers (2)

Nasir Altaf
Nasir Altaf

Reputation: 47

Found the solution here using styled-components, see createGlobalStyle https://scalablecss.com/styled-components-global-styles/

Upvotes: 0

Ramakay
Ramakay

Reputation: 3135

The solution involves creating or modifying your _document.jsx_ or _document.js and implementing the collectStyles to render the inline styles on your page.

This example in the Next repository walks through the process where the App is wrapped with collectStyles and renders the styles inline.

https://github.com/vercel/next.js/blob/master/examples/with-styled-components/pages/_document.js

Note: This collects all style elements that are the children of your App, to selectively include global.css you have to look into the styled components API and parse through the sheet.getStyleElement() potentially.

Upvotes: 1

Related Questions