1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

expressとReactでSSRする際に、DOCTYPEを記述する方法

Posted at

ReactでSSRする際に、DOCTYPEを書く方法がわからず、しばらくハマりました。
解決方法が見つかったので、備忘録的に記しておきます。

Html.tsx
import * as React from 'react'
import App from '../containers/App'

interface Props {}
const Html: React.SFC<Props> = (props: Props) => {
  return (
    <html>
      <head>
        <title>App</title>
      </head>
      <body>
        <div id="app">
          <App /> 
        </div>
        <script src="/client.bundle.js" />
      </body>
    </html>
  )
}

export default Html

このようにHtmlコンポーネントを書いている場合、

serverRoutes.tsx
import * as path from 'path'
import * as express from 'express'
import { Request, Response } from 'express';
import * as React from 'react'
import * as ReactDOMServer from 'react-dom/server'
import { Provider } from 'react-redux'
import { StaticRouter } from 'react-router-dom'
import configureStore from '../store/configureStore'
import Html from '../components/Html'

const store = configureStore()
const router: express.Router = express.Router()

router.get('/client.bundle.js*', (req: Request, res: Response): void => {
  res.sendFile(path.resolve(`./dist${req.url}`))
})

router.get('*', (req: Request, res: Response): void => {
  res.write('<!DOCTYPE html>') // ← これを書く!!
  const context: { url?: string } = {}
  ReactDOMServer.renderToNodeStream(
    <Provider store={store}>
      <StaticRouter location={req.url} context={context} >
        <Html />
      </StaticRouter>
    </Provider>
  ).pipe(res)
})

export default router

res.write('<!DOCTYPE html>')これを書くだけでした。
これだけで結構時間が潰れた。。。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?