LoginSignup
2
0

More than 3 years have passed since last update.

[webpack]初回ビルド時に通知するプラグインを作ってみた!

Last updated at Posted at 2020-12-21

はじめに

webpackのビルド完了時に通知してくれるライブラリでwebpack-build-notifierなどがありますが、見た感じ初回ビルドのみはなかったので、今回はnode-notifierを使って、初回ビルド時に通知してくれるwebpackのプラグインを作ってみました!
webpackの簡単な設定などは済んでいる前提で進めていきます。

以下のサイトを参考にさせていただきました。
node-notifier
簡単な Webpack plugin を作成して Webpack と仲良くなる (ビルド時情報を console.log に表示する)

インストール

デスクトップ通知ができる、node-notifierをインストールします。

## npm
npm install node-notifier

## yarn
yarn add node-notifier

プラグインを作成

適当な名前でファイルを作ります。今回はfirst-build-plugin.jsという名前にしました。

first-build-plugin.js
const notifier = require('node-notifier');

module.exports = class FirstBuildPlugin {
  constructor() {
    this.is_build = false;
  }

  apply(compiler) {
    compiler.hooks.done.tap('FirstBuildPlugin', () => {
      if (!this.is_build) {
        notifier.notify({
          title: 'webpack',
          message: 'ビルドが完了しました!',
          sound: 'Ping',
        });
        this.is_build = true;
      }
    });
  }
};
  • webpackでpluginを参照するときにapplyというのが実行されて、applyはcompilerを引数にとります。
  • compilerからアクセスできるhooksで実行タイミングを設定することができ、doneはコンパイル完了時に呼び出されるhooksです。
  • なので、その中にnode-notifierの通知の記述をしていますが、このままだとビルド時に毎回通知が来てしまうのでif文で初回のみになるようにしています。
  • title,messageで通知のメッセージを、soundで通知オンを設定しています。他にもiconで画像を設定したりなどできます。詳しくはnode-notifierのgithubページを見てみてください。

プラグインの読み込み

webpackの設定ファイルで読み込みます。

webpack.config.js
// 〜 省略 〜 他のライブラリなどインポート
const FirstBuildPlugin = require('./first-build-plugin.js'); // ファイル名や場所によって変えてください

module.exports = {
// 〜 省略 〜 設定など
  plugins: [
    // 〜 省略 〜 他のプラグインなど
    new FirstBuildPlugin(),
  ]
};

// 〜 省略 〜

以下のコマンドを実行します。

webpack --watch



↓こんな感じで表示されます!
image.png

終わりに

ここまで読んでいただきありがとうございます!この記事が少しでもお役に立てたら嬉しいです!
初回ビルドのみじゃなくて、毎回表示したりしたい場合はwebpack-build-notifierですぐ使えるのでオススメです。
webpack5が少し前にリリースされたので見ていきたいですね〜

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