ReactやVueなどでコンポーネントを作成するような場合に
JSXのファイル、テスト用ファイルとStorybook用のファイルなど複数まとめて作ったりしますよね。
その際に雛形を一気に生成できるようにすると効率が上がります。
Plopを使ってそれを実現する方法について解説します。
Plopとは
Plopは、コードジェネレーター用の小さなライブラリ
micro-generator frameworkと呼ばれてたりします。
メリットは大きくは2つです。
- 雛形をコピペで作成する時間の節約
 - チームなどでルールが統一されたファイルの生成
 
特にフルスクラッチでアプリケーションを作る時などに重宝できます。
類似サービスとして、Hygenがあります。

MicrosoftやPayPalなど名だたる企業で使われています。
Plopの使い方
Plopの使い方を解説していきます。
前提の仕様
- index.tsxとstyle.tsを作成(TypeScriptとstyled-components使用)
 - Atomic Designの構成
 
 補足
今回の前提仕様はあくまで例です。
ブログコンテンツを作成するテンプレートを作るなど、様々なケースで使えます。
ディレクトリ構成はこんな感じです。
ディレクトリ構成
- src
  - components
    - atoms
    - molecules
    - organisms
    - pages
- package.json
- generators
  - BaseComponent
作成手順
それでは1つ1つ解説していきます。
インストール
$ npm i -D plop
$ yarn add -D plop
テンプレートとなる雛形ファイルの作成
ファイルをおくためのディレクトリは本記事上ではgenerators/とします。(任意です。)
import React from 'react';
import {DummyText} from './style';
const defaultProps = {};
type Props = {} & typeof defaultProps;
const {{properCase name}} = (props: Props) => {
  return (
    <DummyText>text</DummyText>
  );
};
{{properCase name}}.defaultProps = defaultProps;
export default {{properCase name}};import styled from 'styled-components';
export const DummyText = styled.p``;Plopfileの作成
module.exports = (plop) => {
  plop.setGenerator("component", {
    description: "Create a component",
    prompts: [
      {
        type: "list",
        name: "atomic",
        message: "Choose atomic?",
        choices: [
          { name: "atoms", value: "atoms" },
          { name: "molecules", value: "molecules" },
          { name: "organisms", value: "organisms" },
          { name: "pages", value: "pages" },
        ],
      },
      {
        type: "input",
        name: "name",
        message: "What is your component name?",
      },
    ],
    actions: (data) => {
      const path = `../src/components/${data.atomic}/`;
      const actions = [
        {
          type: "add",
          path: path + "{{pascalCase name}}/index.tsx",
          templateFile: "BaseComponent/index.tsx.hbs",
        },
        {
          type: "add",
          path: path + "{{pascalCase name}}/style.ts",
          templateFile: "BaseComponent/style.ts.hbs",
        },
      ];
      return actions;
    },
  });
};package.jsonにコマンドを追加
"scripts": {
    ...
    "generate": "plop --plopfile generators/index.js",
    ...
  },実行!
$ npm generate
$ yarn generate
まとめ
Plopを使うことで、コードを自動生成することができます。
雛形をそのままコピペしたりして毎回数分を無駄にしている時などあると思いますので、そういう時に使ってみてください!

