kurodakazumichi / issues

0 stars 0 forks source link

Grunt #3

Open kurodakazumichi opened 6 years ago

kurodakazumichi commented 6 years ago

概要

Node.jsを利用したタスク自動化ツール

公式サイト

https://gruntjs.com/

kurodakazumichi commented 6 years ago

gruntのインストール

npm install -g grunt-cli
kurodakazumichi commented 6 years ago

作業ディレクトリの準備

cd ~/
mkdir work && cd $_
npm init
npm install grunt --save-dev
  1. npm initpackage.jsonを作成。
  2. grunt本体をインストール。 グローバル環境にインストールしたgrunt-cliはgruntのコマンドを使うためのもの。 grunt本体は別途インストールする必要がある。

気づいたこと

kurodakazumichi commented 6 years ago

Gruntfile.jsを作る

~/work直下にGruntfile.jsを作成。

module.exports = function(grunt) {

    // config
    grunt.initConfig({

    });

    // plugin

    // tasks
}

プラグインの探し方

kurodakazumichi commented 6 years ago

grunt-contrib-lessを使ってみる

grunt-contrib-lessはcssのメタ言語であるlessを使うためのプラグイン

grunt-contrib-lessのインストール

npm install grunt-contrib-less --save-dev

下準備

cd ~/work
mkdir src
mkdir build
cd src
touch style1.less

style1.lessの内容は以下

/* style1 */
@color1: #6c94be;
@color2: @color1 + #002322;

h1 {
    color: @color1;
}

h2 {
    color: @color2;
}

Gruntfile.jsにタスクを記述する

Gruntfile.js

module.exports = function(grunt) {

    // config
    grunt.initConfig({
+        less: {
+            build: {
+                src:'src/style1.less',
+                dest:'build/style1.css'
+            }
+        }
    });

    // plugin
+    grunt.loadNpmTasks('grunt-contrib-less');

    // tasks
+    grunt.registerTask('default', 'less');
}
  1. コンパイルするファイルパスとビルドした後のファイルパスを定義。
  2. grunt-contrib-lessプラグインのロード
  3. grunt defaultでタスクが実行されるようにタスクを追加。

実際に実行する。

grunt default
kurodakazumichi commented 6 years ago

ターゲット機能について

下準備

ファイル作成: ~/src/style2.less

/* style2 */
@color1: #6c94be;
@color2: @color1 + #002322;

h3 {
    color: @color1;
}

h4 {
    color: @color2;
}

Gruntfile.jsを更新

module.exports = function(grunt) {

    // config
    grunt.initConfig({
        less: {
-            build: {
+            build1: {
                src:'src/style1.less',
                dest:'build/style1.css'
            },
+            build2: {
+                src:'src/style2.less',
+                dest:'build/style2.css'
+            }
        }
    });

    // plugin
    grunt.loadNpmTasks('grunt-contrib-less');

    // tasks
    grunt.registerTask('default', 'less');             // 'grunt' で build1, build2のタスクが実行される
+    grunt.registerTask('task1', 'less:build1');   // 'grunt task1' で build1のタスクが実行される
+    grunt.registerTask('task2', 'less:build2');  // 'grunt task2' でbuild2のタスクが実行される
}

grunt.initConfigの引数の書き方

task: {
    target1{},
    target2{}
}

taskはプラグインと基本的に同じ名前。 target1,target2の部分は自由に名前をつけられる。