iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 4
0
Modern Web

Next + Ant + Apollo Graphql + Mongo 後台系統 製作與發佈系列 第 4

起手式(Client)

Next.js 因為SSR的關係所以會有一些比SPA複雜的設定

先設定 .babelrc

{
  "env": {
    "development": {
      "presets": [
        "next/babel"
      ]
    },
    "production": {
      "presets": [
        "next/babel"
      ]
    },
    "production-digital": {
      "presets": [
        "next/babel"
      ]
    },
    "production-heroku": {
      "presets": [
        "next/babel"
      ]
    },
    "test": {
      "presets": []
    }
  },
  "plugins": [
    [
      "styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ],
    "transform-decorators-legacy",
    [
      "import",
      {
        "libraryName": "antd",
        "style": "css"
      }
    ]
  ]
}

Next.js 本身已經配備有 next/babel 但是有些 plugin 還是要安裝如上面的設定擋

transform-decorators-legacy
styled-components

next.config.js 安裝@zeit/next-css antd 需要

const withCSS = require('@zeit/next-css')
https://github.com/zeit/next-plugins/tree/master/packages/next-css

Next with Ant 接下來在 pages/_document.js 底下打上下面的程式碼

import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
import stylesheet from 'antd/dist/antd.min.css'

export default 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>My page</title>
          {this.props.styleTags}
          <link rel="stylesheet" href="/_next/static/style.css" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <meta charSet="utf-8" />
          <style dangerouslySetInnerHTML={{ __html: stylesheet }} />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

_document.js 原本是next已經包好的內建檔案,next 允許覆蓋所以程式碼會看起來多一些 實際上ant需要的是這個引入
import stylesheet from 'antd/dist/antd.min.css'
另外如果有用 styled-component
getInitialProps 這個是在server端 先去呼叫前端拿到className 在SSR中先定義好與Client 一致化 才不會噴錯 初學者常會卡在這邊

總結

因為SSR的關係所以會有些設定比較繁瑣,只要按照以上方法設定就可以開始使用 Next with Ant or Styled-Components


上一篇
環境篇
下一篇
起手式(Server)
系列文
Next + Ant + Apollo Graphql + Mongo 後台系統 製作與發佈10
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言