既存プロジェクトをRails5.1にアップデートしたので、webpackerを使って、楽できる感じの JS(ES6)とRailsの開発環境を構築してみた
経緯
環境を以下のようにアップデートしたので、webpackerを導入しました。 - Rails 5.1.3 - Ruby 2.4.1
既存プロジェクトにwebpackerを導入する
- 基本的に README を見れば問題ないです
- またのコマンドを打てば、サンプル(大元になるガイド)ファイルも出力してくれるので、乗っかればやりやすいです。
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
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した後に出力します。
default: &default source_path: app/frontend source_entry_path: packs public_output_path: packs cache_path: tmp/cache/webpacker . . .
// Note: You must restart bin/webpack-dev-server for changes to take effect
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ファイルからのインクルード
= 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 で叩く
web: bundle exec rails s # watcher: ./bin/webpack-watcher webpacker: ./bin/webpack-dev-server
{
"scripts": {
"dev": "bundle install && bundle exec foreman start -f Procfile.dev",
"build": "bundle exec rails webpacker:compile",
},
}
開発の際は
yarn dev を叩いて開発
eslintを入れる
yarn add babel-eslint eslint eslint-config-standard eslint-friendly-formatter eslint-loader eslint-plugin-html eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-standard --D
module.exports = {
test: /\.(js|ts|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
options: {
formatter: require('eslint-friendly-formatter')
}
}
でもwebpackerに乗せたくなかったので、コメントアウトしておきました。
.eslintrc はいい感じに