LoginSignup
3
3

More than 5 years have passed since last update.

bowerのパッケージを1つのjsに結合する

Posted at

以下の理由によりbowerのパッケージを1つのjsにまとめたかった

  • htmlからjsロード時のhttpリクエストを減らしたい
  • bower_componentsをpublicに置きたくない
  • パッケージ追加時にhtmlにロードを追加するのが面倒くさい

こんな感じのディレクトリ構成にしたい

├── bower.json
└── public
    ├── index.html
    └── js
        └── lib.js

index.htmlからはlib.jsのみロード

index.html
<script type="text/javascript" src="js/lib.js"></script>

bower.jsonは例えばこんな感じ

bower.json
{
  "name": "hoge",
  "dependencies": {
    "firebase": "^v3.1.0",
    "jQuery": "^3.0.0",
    "js-yaml": "^3.6.1"
  }
}

前提

  • nodejsとnpmはインストール済みとする

実装

packge.jsonを作っておく

package.json
{
}

必要パッケージをインストール

$ npm install --save-dev gulp gulp-filter main-bower-files gulp-concat

gulpfile.jsを作成

gulpfile.js
gulp = require('gulp');
bower = require('main-bower-files');
concat = require('gulp-concat');
filter = require('gulp-filter');

gulp.task('bowerJS', function() {
  jsFilter = filter('**/*.js');
    gulp
      .src(bower())
      .pipe(jsFilter)
      .pipe(concat('lib.js'))
      .pipe(gulp.dest('public/js/'));
});

gulpfileを実行
public/js/lib.jsが作成される

$ ./node_modules/gulp/bin/gulp.js bowerJS

最終的なディレクトリ構成
(npmとbowerのinstallで作成されるファイルは省く)

├── bower.json
├── packge.json
├── gulpfile.js
└── public
    ├── index.html
    └── js
        └── lib.js

補足

こんなパターンが発生

  • bowerのパッケージのディレクトリ構成が独自
  • min.jsをlib.jsに結合したい

bower.jsonに明示的にjsファイル名を指定する

bower.json
{
  "name": "hoge",
  "dependencies": {
    "firebase": "^v3.1.0",
    "jQuery": "^3.0.0",
    "js-yaml": "^3.6.1"
  },
  "overrides": {
    "firebase": {
      "main": "firebase.js"
    },
    "jQuery": {
      "main": "jquery.min.js"
    },
    "js-yaml": {
      "main": "js-yaml.min.js"
    }
  }
}
3
3
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
3
3