Browserify + gulp で一部 JS を除外して実行する方法

はじめに

今日は Browserify + gulp の環境で、一部のファイルを除外して Browserify を実行する方法を紹介します。

Browserify
17.0.0
gulp
4.0.2
through2
4.0.2
目次
  1. 下準備
  2. gulpfile.js 実装方法
  3. おわりに

1. 下準備

今回使用したファイルや構成などは以下の通りです。

gulpfile.js については「2. gulpfile.js 実装方法」でご紹介します。

/path/to/my-project/
  ├ public/
  │  └ index.html
  │
  ├ src/
  │  ├ entries/
  │  │  ├ smp1.js
  │  │  ├ smp2.js
  │  │  ├ smp3.js
  │  │  └ smp4.js
  │  │
  │  └ modules/
  │     └ sample.js
  │
  ├ gulpfile.js
  └ package.json
/public/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Browserify Sample</title>
  <script src="smp1.js"></script>
  <script src="smp2.js"></script>
  <script src="smp3.js"></script>
  <script src="smp4.js"></script>
</head>
<body>
  結果は console.log で出力
</body>
</html>
/src/entries/smp1.js
// smp2.js も同様
const { debug } = require('../modules/sample.js');

debug(`One`);
/src/entries/smp3.js
// smp4.js も同様
console.log('Three');
/src/modules/sample.js
module.exports = {
  debug: (value) => {
    console.log('Debug: ' + value);
  }
}
/package.json
{
  "private": true,
  "devDependencies": {
    "browserify": "^17.0.0",
    "gulp": "^4.0.2",
    "through2": "^4.0.2"
  }
}

あとは下記コマンドなどで Browserify と gulp、through2 をインストールしてください。

cd /path/to/my-project/
npm i

2. gulpfile.js 実装方法

下記サンプルでは src/entires 内の 全JS ファイルを Browserify の対象としつつ、その中にある smp3.js と smp4.js は対象外としています。

/gulpfile.js
const { dest, series, src, task } = require('gulp');
const browserify = require('browserify');
const through2 = require('through2');

// JS ソース
const jsBase = './src/entries';
const jsSrc = `${jsBase}/**/*.js`;

// JS 出力先
const jsDest = `./public`;

// Browserify しない JS
const notBrwsrfySrc = [
  `${jsBase}/smp3.js`,
  `${jsBase}/smp4.js`,
];

// Browserify あり
task('js-browserify', () => {
  return src(jsSrc, { ignore: notBrwsrfySrc })
    // Browserify
    .pipe(through2.obj((file, enc, callback) => {
      browserify(file.path)
        .bundle((err, buf) => {
          file.contents = buf;
          callback(err, file);
        });
    }))
    // public フォルダに出力
    .pipe(dest(jsDest));
});

// Browserify なし
// (何も処理せず public に出力しています)
task('js-compile', () => {
  return src(notBrwsrfySrc, { base: jsBase })
    .pipe(dest(jsDest));
});

task('default', series('js-browserify', 'js-compile'));

上記サンプルでは、コンパイルは下記コマンドなどで実行します。

cd /path/to/my-project/
npx gulp

正常に完了すれば、/public の中に smp1.js ~ smp4.js のファイルが生成されます。

今回は Browserify 以外の処理を入れていませんが、pipe() で Babel や terser を使うことも出来ます。

3. おわりに

対象外ファイルの指定について、今回はファイルごとに指定していますが、gulp.src() の ignore オプションでは glob が使えるのでフォルダでの指定なども可能です。

/gulpfile.js
// Browserify しない JS
const notBrwsrfySrc = [
  `${jsBase}/foo/**/*.js`,
];