Skip to content

Instantly share code, notes, and snippets.

@tagty
Created March 29, 2020 03:46
Show Gist options
  • Save tagty/3a0d23ae1c2395d07482dd45a24a2d88 to your computer and use it in GitHub Desktop.
Save tagty/3a0d23ae1c2395d07482dd45a24a2d88 to your computer and use it in GitHub Desktop.
railsとwebpackを使ったSPAを本番環境で動かすにはどうすればよいか?

前回は開発環境について説明した。
今回は本番環境について説明する。
本番環境ではコンパイルしたJSをviewが読み込むように設定する。
コードはこちら

フロントエンド

こちらを参考にして、本番環境用のwebpackの設定をする。
webpack-merge を使って、環境ごとにwebpackの設定ファイルを作れるようにした。

frontend/config/webpack.common.js

module.exports = {
  entry: { apps: "./frontend/src/apps.js" }
};

frontend/config/webpack.prod.js

const path = require("path");
const merge = require("webpack-merge");
const common = require("./webpack.common.js");
const ManifestPlugin = require("webpack-manifest-plugin");

module.exports = merge(common, {
  mode: "production",
  output: {
    filename: "[name].bundle.js",
    path: path.resolve("public/assets"),
    publicPath: "/assets/"
  },
  plugins: [new ManifestPlugin()]
});

Webpack Manifest Pluginを用いて、manifest.json を作成し、pathの解決をする。

public/assets/manifest.json

{
  "apps.js": "/assets/apps.bundle.js"
}

ビルドスクリプトを用意する。

package.json

{
  "scripts": {
    "build": "webpack --config frontend/config/webpack.prod.js"
  }
}

yarn build を実行し、コンパイルしたjsを public/assets/apps.bundle.js に設定できる。

$ yarn build
yarn run v1.22.4
$ webpack --config frontend/config/webpack.prod.js
Hash: c61079565fad3b54eded
Version: webpack 4.41.4
Time: 68ms
Built at: 2020-03-28 19:36:45
         Asset      Size  Chunks             Chunk Names
apps.bundle.js  1.03 KiB       0  [emitted]  apps
 manifest.json  41 bytes          [emitted]  
Entrypoint apps = apps.bundle.js
[0] ./frontend/src/apps.js 179 bytes {0} [built]
✨  Done in 1.63s.

Rails

本番環境の場合は、コンパイル済みのjsを読み込むようにする。

app/helpers/application_helper.rb

module ApplicationHelper
  def webpack_asset_path(path)
    return "http://localhost:3500/#{path}" if Rails.env.development?

    host = Rails.application.config.action_controller.asset_host
    manifest = JSON.parse(File.read(Rails.root.join('public', 'assets', 'manifest.json')))
    path = manifest[path]
    "#{host}/#{path}"
  end
end

本番モードでサーバーを起動する。

$ RAILS_ENV=production rails s
=> Booting Puma
=> Rails 5.2.4.1 application starting in production
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.2 (ruby 2.6.5-p114), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: production
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

まとめ

今回は railswebpack を使ったSPAを本番環境で動かす方法を紹介した。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment