LoginSignup
16
14

More than 5 years have passed since last update.

Sprockets4を使ってRailsアプリケーションのJavaScriptをBabelで書く

Last updated at Posted at 2015-07-05

sprockets-es6 を使う方法(http://magazine.rubyist.net/?0050-ECMAScript2015 )ではなくて
sprockets-railsの4系を使ってみたかったので試した記録です。

とはいえまだ開発中なので

Add support for Sprockets 4.x. by Andreis13 · Pull Request #259 · rails/sprockets-rails

のブランチを使いました。

アプリケーションを用意します。Railsは5系を使いました。

$ git clone https://github.com/rails/rails
$ ./rails/railties/exe/rails -v
Rails 5.0.0.alpha
$ ./rails/railties/exe/rails new myapp

Gemfileを書き換えます

Gemfile(抜粋)
source 'https://rubygems.org'

gem 'babel-transpiler'
gem 'sprockets', git: 'https://github.com/rails/sprockets.git'
gem 'sprockets-rails', git: 'https://github.com/Andreis13/sprockets-rails.git', branch: 'sprockets-4'

gem 'arel', git: 'https://github.com/rails/arel.git'
gem 'rails', git: 'https://github.com/rails/rails.git'

sass-rails はこれからRails5対応するのかな? 有効にしていると依存関係の都合でまだ使えないので無効にします。
ついでに予期せぬ事態が起きそうなので turbolinks も外します(というより途中動かない原因がよくわからなくて試しに外してみました)。

Gemfile(抜粋)
# gem 'sass-rails', '~> 5.0'
# gem 'turbolinks'

適当にページ作ってみます

./bin/rails generate scaffold book title:text

app/assets/javascripts/ 以下に *.es6 という名前でES6(2015)のコードを書きます。
なんでもよかったので前述のるびま記事のコードを一部拝借しました。

character.es6
'use strict';

class Character {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.health_ = 100;
    }
    attack(character) {
        this.x += 10;
        character.x -= 10;
        character.health_ -= 10;
    }
    get health() {
        return this.health_;
    }
}

モジュールのロードはES6式ではなくSprockets式で……

book.es6
//= require character

let c1 = new Character(0, 0);
let c2 = new Character(0, 0);
c1.attack(c2);

console.log('C1: ', c1);
console.log('C2: ', c2);

rails s して ‘http://localhost:3000/books‘ を開きます

kobito.1436075488.763925.png

動いていそう。

books-source*.es6 の中身はなぜか空?)

動かした過程でいろいろいじったのを記憶をもとにメモ

config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( application.css )
Rails.application.config.assets.precompile += %w( application.js )
application.html.erb
  <%= stylesheet_link_tag    'application', media: 'all' %>
  <%= javascript_include_tag 'application' %>
16
14
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
16
14