二)NextJS集成Styled Components

2021-05-30 03:04

阅读:746

标签:ini   color   glob   creat   title   com   als   sync   log   

打开前一篇中建立的NextJS项目,添加以下依赖:
npm install babel-plugin-styled-components --save-dev
npm install styled-components --save

再添加以下内容:
1:touch .babelrc //添加babel配置文件
内容如下:

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

2: 打开pages/indes.js,替换代码如下

import styled from ‘styled-components‘

const Title = styled.h1`
  font-size: 50px;
  color: ${({ theme }) => theme.colors.primary};
`

export default function Home() {
  return My page
}

3:pages/_app.js, 替换代码如下

import { createGlobalStyle, ThemeProvider } from ‘styled-components‘

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
`

const theme = {
  colors: {
    primary: ‘#0070f3‘,
  },
}

export default function App({ Component, pageProps }) {
  return (
    
      >
  )
}

4: pages/_document.js,替换代码如下

import Document from ‘next/document‘
import { ServerStyleSheet } from ‘styled-components‘

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          
            {initialProps.styles}
            {sheet.getStyleElement()}
          >
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}

二)NextJS集成Styled Components

标签:ini   color   glob   creat   title   com   als   sync   log   

原文地址:https://www.cnblogs.com/Andy1982/p/14695814.html


评论


亲,登录后才可以留言!