フロントエンド

Gruntの環境構築

Grunt(グラント)とは

GruntはNode.js上で動作するタスクランナーです。
Grunt自身でビルドなどは行わずそれぞれのタスクでプラグインを追加して「ファイルの圧縮」や「minify」を行うことができます。

類似のNode.js上で動作するタスクランナーとしてGulp(ガルプ)があります。

実行環境

  • Windows10
  • Node: 18.15.0
  • Grunt: 1.6.1

環境構築の方法

作業用ディレクトリ作成

まず作業用のディレクトリを作成し、ディレクトリ内に移動します。

mkdir grunt-sample
cd grunt-sample

Gruntのインストール

Gruntをインストールするためpackage.jsonファイルを作成し、Gruntをインストールします。

npm init -y
npm i -D grunt

Gruntfile.jsの作成

Gruntを使用する際、タスクという単位で処理を実行していきます。
その処理をまとめたものがGruntfile.jsです。
package.jsonと同じディレクトリ階層にGruntfile.jsを作成します。

touch Gruntfile.js

Gruntfile.jsが作成できたら設定ファイルの雛形を作成します。

const grunt = require('grunt');  
  
module.exports = function() {  
    grunt.initConfig({  
        pkg: grunt.file.readJSON('package.json')  
    });  
    grunt.registerTask('default', function() {  
        const gruntConfig = grunt.config.get(['pkg']);  
        const {name, version} = gruntConfig;  
  
        grunt.log.writeln(`name: ${name}`);  
        grunt.log.writeln(`version: ${version}`);  
        grunt.log.write('echo test message...').ok();  
    });  
};

package.jsonへscriptの追記

コマンドラインよりnpm runで実行できるようにpackage.jsonscriptに実行コマンドを記載します。

{
  "name": "grunt-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "grunt": "grunt default"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "grunt": "^1.6.1"
  }
}

Gruntの使い方

Gruntの実行

先程package.jsonscriptに追加したコマンドを実行します。

npm run grunt

Gruntの実行結果

npm run gruntを実行するとコマンドライン上に下記のように結果が表示されます。

$ npm run grunt                                                     

> grunt@1.0.0 grunt
> grunt default

Running "default" task
echo test message...OK
name: grunt
version: 1.0.0

Done.

Process finished with exit code 0

以上でGruntの最小構成の環境ができあがりました。
ここから様々なプラグインを追加することにより、SCSSをCSSにコンパイルすることや、ファイルにminifyを実行しファイルサイズを圧縮することもできます。

今回作成したgruntのプロジェクトファイルはコチラからダウンロードできます。

-フロントエンド
-,