RailsでBowerの導入

( javascript )

javascriptのパッケージ管理がしたくてbowerというパッケージ管理ツールをhttp://www.frustration.me にインストールしてみました。 (ブランチ切って試してみました・・・)

とりあえず、バージョンが古いので最新のものにインストールします。

$ node -v 
v0.6.19


$ brew install node

==> Upgrading 1 outdated package, with result:
node 0.10.7
==> Upgrading node
Beginning with 0.8.0, this recipe now comes with npm.
It appears you already have npm installed at /usr/local/lib/node_modules/npm.
To use the npm that comes with this recipe, first uninstall npm with
`npm uninstall npm -g`, then run this command again.

If you would like to keep your installation of npm instead of
using the one provided with homebrew, install the formula with
the `--without-npm` option.
Error: An unsatisfied requirement failed this build.

npm をまずアンインストールしてほしいとのこと

$ npm uninstall npm -g

再度実行します。

$ brew upgrade node
$ node -v
v0.10.7

これで最新版になった。 次にbowerをインストール

$ npm install -g bower

これでインストール完了。

とりえず、検索でどうなるか確認。

bower search backbone
Search results:

    backbone git://github.com/documentcloud/backbone.git
    backbone-amd git://github.com/amdjs/backbone
    backbone.stickit git://github.com/NYTimes/backbone.stickit.git
    backbone.marionette git://github.com/marionettejs/backbone.marionette
    backbone.wreqr git://github.com/marionettejs/backbone.wreqr.git
・
・
・

てな感じでbackboneに関連するプラグインがどどどっと出力される

試しにインストールすると、ホームディレクトリに生成されてしまうので アプリごとに管理したいところ

$ bower install jquery
bower cloning git://github.com/components/jquery.git
bower cached git://github.com/components/jquery.git
bower fetching jquery
bower checking out jquery#2.0.2
bower copying /Users/pp_kupepo_gattyanmo/.bower/cache/jquery/29cb4373d29144ca260ac7c3997f4381
bower installing jquery#2.0.2

ここからRaisに組み込んでいきます。

$ bower init
name: [frustration]
version: [0.0.0]
main file: []
add current components as dependencies? (y/n): [y] y
add commonly ignored files to ignore list? (y/n): [y]

そうするとカレントディレクトリに以下のファイルが作成されます。 このファイルでプラグインの管理を行います。

{
  "name": "frustration",
  "version": "0.0.0",
  "dependencies": {
    "jquery": "~2.0.2"
  },
  "ignore": [
    "**/.*",
    "node_modules",
    "components"
  ]
}

現状の設定だとグローバルの設定なのでダウンロードがプロジェクト単位でできないので .bowerrcファイルをプロジェクトディレクトリ直下に保存する。 デフォルトは~/.bowerrcを参照するようだ。

{
  "directory": "vendor/assets/javascripts/components",
  "json": "bower.json",
  "searchpath": [
    "https://bower.herokuapp.com"
  ]
}

これでbower installすると指定のディレクトリに保存される。

Railsの場合

application.rbでパスを通るようにする

    # for bower
    config.assets.paths << Rails.root.join('vendor', 'assets', 'javascripts', 'components')

applicatio.jsでパスの再設定を行う。

//= require components/jquery/jquery.js
//= require components/jquery-ui/ui/jquery-ui.js

これでRailsの場合は完了です。

所感

jsもbundlerのように管理できるようになったのは大変便利作業です。 version上がることごとにサイト確認してwgetしてこないといけないし、コマンド一発でプラグインの削除・検索・バージョンのアップ・ダウングレードもできてしまうのは進化であるのです。

ですが、まだ

  • version 管理されていないプラグインある
  • 本番環境にnodeが入っていない・bowerが使えない

ときがあるのでそこは共存なり、一旦保留なりしたほうが良いかもしれません。。。 また、後者のときはいけてないけどパッケージも合わせてコミットするのが良いかもしれない。

Ref

ここにパッケージが登録されています