LoginSignup
1
2

More than 5 years have passed since last update.

npmライブラリのBootstrap4をgulpで管理するとき

Posted at

色々躓いたので備忘録。

最近npmでJSやCSSを管理するのが流行り?と感じたので、そっちへシフトしたときの構築です。

まず、gulpや諸々インストールされているものとして書きます。
また、browserify、vinyl-source-stream等は処理しているものとします。

jQueryを先ずインストールします

console
$ npm install jquery --save

node_modulesディレクトリ内にjqueryディレクトリがあればOK。

次にBootstrapをインストールします

console
$ npm install bootstrap@4.0.0-alpha.6 --save

こちらもnode_modules内にbootstrapディレクトリがあればOK。

Bootstrap4を使うためにもうひとつ必要なものがあるので、そちらもインストールします。

Tetherをインストール

console
$ npm install tether --save

このライブラリがないと正しくコンパイルができないようです。

gulpfile.js

以下のコードは当方の環境の設定なので、ディレクトリや構造は各々で設定をお願いします。

gulpfile.js
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

var config = require('../config.js');

// JavaScript
gulp.task('js', function() {
    return browserify({
        entries: ['js-dev/script.js']
    })
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe($.uglify())
    .pipe(gulp.dest(config.paths.cmnDir+'js/'));
});

JavaScriptでjQueryとBootstrapを読み込んでみる

まず、間違ったやり方で書くと、BootstrapがjQueryを認識しません。

script.js
var $ = require('jQuery');
require('bootstrap');

$(function() {
    $('h1').css('color', 'blue');
});

上記の内容だと、Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.となりBootstrapが正しくIncludeされませんでした。

var $ = require('jQuery')を以下のように書き直します。

script.js
window.jQuery = window.$ = require('jQuery');
window.Tether = require('Tether');
require('bootstrap');

(function($) {
    "use strict";

    $('h1').css('color', 'blue');
})(jQuery);

自分は、$から書くよりjQueryを使う癖がついてしまったので、こんな書き方してますがもちろんwindow.$のみでも問題ありません。

jQueryだけ使う場合は、最初の書き方で充分なんですけどね。
でも色々追加するときを考えると上記で書いたほうがいいかな。

BootstrapのScssをインポートする

こちらはもう普通にnode_modulesディレクトリから直接読み取りにいってます。

app.scss
@import "./node_modules/bootstrap/scss/bootstrap.scss";

ディレクトリまでの階層は各々調整してください。
自分の場合は、public/assets/scss/内に配置しているので、
@import "../../../node_modules/ 〜中略〜 /bootstrap.scss";このような形になってます。

1
2
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
1
2