LoginSignup
3
6

More than 5 years have passed since last update.

webpack-html-plugin + ejs で SSR する

Last updated at Posted at 2017-11-09

Router未対応だが、とりあえずイニシャルページが確定的で事前にコンパイルできるケースでSSRする。

やり方

  • ejs で html をビルド時に SSR して埋めてしまう。
  • その時のコンテキストは node なので babel-register を叩けば動くはず

コード

src/ssr/index.ejs
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <%
      require('babel-register');
      const React = require('react')
      const ReactDOM = require('react-dom/server');
      const App = require('../components/App').default;
    %>
    <div id='app-root'><%= ReactDOM.renderToString(React.createElement(App)) %></div>
    <script src="index.bundle.js"></script>
  </body>
</html>
webpack.config.js
const path = require('path')
const webpack = require('webpack')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ENV = process.env.NODE_ENV || 'development'

module.exports = {
  entry: { /* */ },
  output: { /* */ },
  module: { /* */ },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src/ssr/index.ejs'),
      minify: false,
      inject: false
    })
  ]
}

html-webpack-plugin で minify してしまうと SSR の引き継ぎに失敗するので、その点だけ注意

3
6
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
3
6