LoginSignup
26
26

More than 5 years have passed since last update.

RailsでES6を使う

Posted at

RailsでJSファイルごとの依存関係の管理やJS,CSSのminifyを担当しているSprocketsですが、最近ES6のサポートをfeatureとして取り込んできました。

まだfeatureブランチで作業している最中なのでそのまま使うことはできないのですが、別のgem(josh/sprockets-es6)を使うことで、現状でもRailsでES6を試すことができます。

ES6へのtranscompilerにはbabel(ex 6to5)を使っているようです。

試しに使ってみたので、その方法をまとめておきます。

まずは普通にRailsプロジェクトを立ち上げます

$ rails -v
Rails 4.2.0

$ rails new es6 --skip-bundle --skip-test-unit 
       exist
      create  README.rdoc
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/assets/images/.keep
      ~~~~
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.keep

次にGemfileに以下を追記します。

Gemfile
gem 'sprockets', '~> 3.0.0.beta.8'
gem 'sprockets-es6', require: 'sprockets/es6'

これでbundle installを実行すれば準備完了です。

さて、es6で書くファイルは全て .es6 という拡張子にする必要があります。

app/assets/javascripts/greeting.es6
class Greeting {
    constructor(name) {
        this.name = name;
    }
    say() {
        return `Hello ${this.name} !!`;
    }
}

console.log(new Greeting("John").say()); // Hello John!!

楽しいですね。

.jsファイルを .es6 ファイルからrequire出来なかったり、まだまだproductionで使えるものではないと思いますが、今後に期待していきたいですね。

26
26
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
26
26