LoginSignup
12
12

More than 5 years have passed since last update.

Gruntタスクをモジュール化して管理する

Posted at

Gruntfile.jsを10行にした話@watilde

このエントリを読んでこのエントリを書いたんですが、もっと構成を簡単にできそうだったので書きなおしてみました。

構成

  • Gruntfile.js
  • package.json
  • /Gruntconfig
    • タスクモジュール

先のエントリではconfig.js/Gruntconfig内のモジュールを自動で読み込むようにしたのですが、そもそも自動で読むならconfig.jsとしてファイルを分ける必要がありませんでした。

なのでconfig.jsでやっていたことをGruntfile.jsに記述して、/Gruntconfigフォルダにはタスクのモジュールだけを入れるようにしました。

Gruntfile

Gruntfile.js
module.exports = function(grunt) {
  var configDir, fs, packageJson, path;
  configDir = "Gruntconfig";
  fs = require("fs");
  path = require("path");

  fs.readdirSync(configDir).forEach(function(filePath) {
    var fileName, modulePath, stats;
    modulePath = path.join(__dirname, configDir, filePath);
    stats = fs.statSync(modulePath);
    fileName = filePath.split(".")[0];
    if (stats.isFile() && filePath.charAt(0) !== "." && filePath.charAt(0) !== "_") {
      return grunt.config.set(fileName, require(modulePath));
    }
  });

  packageJson = grunt.file.readJSON("package.json");
  Object.keys(packageJson.devDependencies).slice(1).forEach(grunt.loadNpmTasks);

  grunt.registerTask("default", ["connect", "watch"]);
};

タスクモジュール

/Gruntconfigに置くタスクモジュールは以下のような記述。置いたモジュールは自動で読み込まれます。使いたいモジュールのgruntプラグインはpackage.jsondevDependenciesに記述されている必要があります。

/Gruntconfig/connect.js
/* connect*/
module.exports = {
  dist: {
    options: {
      port: 5000,
      base: ".",
      open: "http://localhost:5000"
    }
  }
};
/Gruntconfig/watch.js
/* watch*/
module.exports = {
  reload: {
    files: ["./*.html", "./css/*.css", "./js/*.js"],
    options: {
      livereload: true
    }
  }
};

その他変更点

  • ファイル名の先頭が.だった場合に無視する
  • ファイル名の先頭が_だった場合に無視する

と、.DS_Storeとかを無視するのと、一時的に読み込みたくないモジュールはファイル名の先頭に_をつけることで読み込まないようにできます。(フォルダの階層を一個深くすることでも読み込まないようにできます)


前よりスッキリしました。

今回自前で書いてみましたが、すでに同じようなプラグインがあってインストールすれば簡単に使えたりします。

Grunt深い。

12
12
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
12
12