Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2912

Reactコンポーネントの雛形生成を自動化するスクリプトファイルを作る

$
0
0

エンジニアにとって無駄な作業はストレス。
繰り返しの作業を自動化したい。

という事でコンポーネントファイルを自動生成するスクリプトを書いた。

スクリプトファイルの使い方

まずは使い方から。
ルートディレクトリで

bash ./etc/scripts/make-component-template.sh components Layout

というように、ディレクトリ名とコンポーネント名を指定するだけ。


ルートディレクトリ直下にcomponentsディレクトリがある事を想定しています。
carbon (1).png

自動生成するファイル

./etc/scripts/make-component-template.sh components Layoutを実行すると以下のファイルを生成します。

components
└── Layout
    ├── Layout.jsx
    ├── index.jsx
    └── style.css

ファイルの中身

index.jsx
export{default}from'./Layout'
Layout.jsx
importReact,{memo}from'react'importPropTypesfrom'prop-types';importstylefrom'./style.css'Component.propTypes={};constComponent=memo(()=>{return(<div></div>);});functionContainer(props){return<Component/>}Container.propTypes={};exportdefaultContainer

style.cssは空です。

コンポーネントを生成するためのシェルスクリプト

シェルスクリプト

etc/scripts/make-component-template.sh
#!/bin/bashif[$# -ne 2 ];then
  echo"指定された引数は$#個です。" 1>&2
  echo"実行するには2個の引数が必要です。" 1>&2
  echo"例: components(ディレクトリ名) Layout(コンポーネント名)" 1>&2
  exit 1
fi

DIR=$1COMPONENT=$2TARGET="$DIR/$COMPONENT"if[-e"$TARGET"];then
  echo"ディレクトリ'$TARGET'は既に存在します。" 1>&2
  exit
fi

mkdir"$TARGET"touch"$TARGET/index.jsx"echo"export { default } from './$COMPONENT'">"$TARGET/index.jsx"cp etc/scripts/component-template.txt "$TARGET/$COMPONENT.jsx"touch"$TARGET/style.css"

Reactコンポーネントのテンプレート

etc/scripts/component-template.txt
import React, { memo } from 'react'
import PropTypes from 'prop-types';
import style from './style.css'


Component.propTypes = {

};

const Component = memo(() => {
  return (
    <div>

    </div>
  );
});



function Container(props) {

  return <Component />
}

Container.propTypes = {

};

export default Container

補足

  • 生成されるReactコンポーネントの構成を変更したい場合は、component-template.txtファイルを書き換えてください。
  • eslintでエラーが出たりprettierで整形されないように、component-templateの拡張子をtxtにしています。

Enjoy Hacking!😎


Viewing all articles
Browse latest Browse all 2912

Trending Articles