LoginSignup
6
4

More than 5 years have passed since last update.

[Rails5.1][webpacker] 既存プロジェクトをRails5.1にアップデートしたので、webpackerを使って、楽できる感じの JS(ES6)とRailsの開発環境を構築してみた

Last updated at Posted at 2017-08-22

経緯

環境を以下のようにアップデートしたので、webpackerを導入しました。
- Rails 5.1.3

既存プロジェクトにwebpackerを導入する

  • 基本的に README を見れば問題ないです
    • またのコマンドを打てば、サンプル(大元になるガイド)ファイルも出力してくれるので、乗っかればやりやすいです。
Gemfile
gem 'webpacker', '~> 2.0'
# OR if you prefer to use master
gem 'webpacker', git: 'https://github.com/rails/webpacker.git'

gem 'foreman'
bundle install
./bin/rails webpacker:install

vueを導入

  • elmやreactも導入するコマンドがあります
./bin/rails webpacker:install:vue
config/webpack/loaders/vue
const { env, settings } = require('../configuration.js')

const isProduction = env.NODE_ENV === 'production'
const extractCSS = !settings.dev_server.hmr

module.exports = {
  test: /\.vue$/,
  loader: 'vue-loader',
  options: {
    extractCSS: isProduction || extractCSS
  }
}

既存環境との両立

  • 既存の古いJSもたくさんあったので、一気にwebpacker環境に持っていくのは大変そうだったため、共存させつつ、少しずつ移行していくことにしました。
  • webpacker環境のファイル構成を app/frontend 以下に構築します。
  • app/frontend/packs 以下のファイルを、 public/packs 以下に、 Compileした後に 出力します。
config/webpacker.yml
default: &default
  source_path: app/frontend
  source_entry_path: packs
  public_output_path: packs

.
.
.
config/webpack/development.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const sharedConfig = require('./shared.js');
const { settings, output } = require('./configuration.js');

module.exports = merge(sharedConfig, {
  devtool: 'cheap-eval-source-map',

  output: {
    pathinfo: true
  },
.
.
.


});

viewファイルからのインクルード

index.slim
= stylesheet_pack_tag 'hoge/style/main' # /public/packs/hoge/style/main.css を読みます
= javascript_pack_tag 'hoge/main' # /public/packs/hoge/main.js を読みます
= javascript_include_tag 'http://d3js.org/d3.v3.min.js' # おなじみのタグも使えます

開発の為の工夫

webpacker環境下のファイルを編集したらブラウザがライブリロードされてほしい

  • rails s と合わせて、 webpackerもwatchしたまま走らせたい
    • formanを使って、両方を一つの npm run script で叩く
Procfile.dev
web: bundle exec rails s
# watcher: ./bin/webpack-watcher
webpacker: ./bin/webpack-dev-server
package.json
{
  "scripts": {
    "dev": "bundle install && bundle exec foreman start -f Procfile.dev",
    "build": "bundle exec rails webpacker:compile",
  },
}

開発の際は

yarn dev を叩いて開発

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