---
title: BrowserifyとBowerを組み合わせる
tags: ["Bower", "Browserify", "Gulp", "JavaScript"]
categories: ["Programming", "JavaScript", "Browserify"]
date: 2014-12-28T05:56:12Z
updated: 2014-12-28T05:56:12Z
---

[前回](http://blog.ik.am/#/entries/306)に続き、今回はbowerとも連携する。

### Bowerインストール

``` bash
$ npm install -g bower
```

### Bowerプロジェクト初期化

`bower init`でデフォルト値を入力する。

``` bash
$ bower init
? name: hello-bower
? version: 0.0.0
? description:
? main file: index.js
? what types of modules does this package expose?:
? keywords:
? authors: making
? license: MIT
? homepage:
? set currently installed components as dependencies?: Yes
? add commonly ignored files to ignore list?: Yes
? would you like to mark this package as private which prevents it from being accidentally published to the regist? would you like to mark this package as private which prevents it from being accidentally published to the registry?: No

{
  name: 'hello-bower',
  main: 'index.js',
  version: '0.0.0',
  authors: [
    'making'
  ],
  license: 'MIT',
  ignore: [
    '**/.*',
    'node_modules',
    'bower_components',
    'test',
    'tests'
  ]
}

? Looks good?: Yes
```

### jQueryインストール
一例としてjQueryをインストールしてみる。

``` bash
$ bower install --save jquery
```

### debowerify
BowerでinstallしたライブラリをBrowserifyの`require`から読み込めるようにdebowerifyで変換を書ける。

インストール(`bower`じゃなくて`npm`なので注意)。

``` bash
$ npm install --save-dev debowerify
```

Gulpfileに設定する。`browserify`に`transform`する形。

``` javascript
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var debowerify = require('debowerify');

gulp.task('browserify', function () {
    return browserify('./index.js', {debug: true})
        .transform(debowerify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./'));
});
```

### アプリ修正
前回と`greeter.js`はそのままにして、`index.js`を以下のように修正する。

``` javascript
var Greeter = require('./greeter.js');
var $ = require('jquery');
var greeter = new Greeter('World');

$(function() {
    $('#hello').on('click', function(){
	alert(greeter.greet());
    });
});
```

次に、これを呼び出す`index.html`を作成。

``` html
<!DOCTYPE html>
<html>
<head lang="ja">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
  <button id="hello">Click</button>
  <script src="bundle.js"></script>
</body>
</html>
```

### ビルド

``` bash
$ gulp browserify
```

`index.html`をブラウザで開き、ボタンをクリックすると


![image](https://qiita-image-store.s3.amazonaws.com/0/1852/666703ee-0fa4-cf97-09f3-fa5c9b3d5990.png)

できた。

----

あとで気づいたけど、わざわざBower持ち出さなくても、`npm`だけでもいけた。

`npm install --save-dev jquery`だけで、bower関連不要
