2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Strapi v4でカスタムプラグインを作ろう!

Last updated at Posted at 2023-07-11

概要

Strapi(v4)でカスタムプラグインを作成する方法を紹介します。

言語はTypeScriptを使用しています。

プラグインの作成

以下のコマンドを実行

npm
npm run strapi generate plugin

yarn
yarn strapi generate plugin

プラグインの名前はどうする?と聞かれるので、任意のプラグイン名を入力します。
(今回はsample-pluginという名前で作成)

$ strapi generate plugin
? Plugin name sample-plugin

Pluginのディレクトリ構成

プラグインを作成するとsrc/plugins配下にプラグインのフォルダが作成されます。

├──admin
│   └── src
│       ├── components
│       ├── index.tsx
│       ├── pages
│       ├── pluginId.ts
│       ├── translations
│       └── utils
├── custom.d.ts
├── dist
├── node_modules
├── package.json
├── server
├── strapi-admin.js
├── strapi-server.js
├── tsconfig.json
├── tsconfig.server.json
├── yarn-error.log
└── yarn.lock

admin/src配下ではプラグインのページを構成するファイルが置かれており、Reactで書かれている。

Configファイルの設定

管理画面で作成したプラグインを使用できるようにするためには設定ファイルを追記する必要があります。

プロジェクトのルートディレクトリにあるconifgフォルダにplugins.tsを作成し、以下の内容を記述

export default {
  'sample-plugin': {
    enabled: true,
    resolve: './src/plugins/sample-plugin'
  },
}

管理画面で確認する

プラグインを管理画面で表示させるためにはプラグイン構成ファイルをビルドする必要があります。

# プラグインの構成フォルダ配下に移動
cd src/plugins/sample-plugin

# ビルドする
yarn build # yarn
npm run build # npm

# プロジェクトルートに移動し、アプリを起動
cd ../../../
yarn develop # yarn
npm run develop  # npm

管理画面にログインすると左側のメニューから、作成したプラグインが確認できます。

スクリーンショット 2023-07-06 8.54.06.png

プラグインの中身を作成する

今回は簡単なボタンコンポーネントを表示させてみます。

admin/src/components配下にカスタムボタンコンポーネントを作ります。

src/plugins/sample-plugin/admin/src/components/Button/index.tsx
import React from 'react';
import Styled from 'styled-components'

const CustomButton = () => {
  return (
    <Button onClick={() => {alert('hello');}}>Button</Button>
  );
}

const Button = Styled.button`
  display: inline-block;
  color: #BF4F74;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid #BF4F74;
  border-radius: 3px;
  display: block;
`;

export default CustomButton;

HomePage/index.tsxで上記で作成したコンポーネントを表示させます。

src/plugins/sample-plugin/admin/src/pages/HomePage/index.tsx
/*
 *
 * HomePage
 *
 */

import React from 'react';
import CustomButton from '../../components/CustomButton';

const HomePage = () => {
  return (
    <div>
      <CustomButton></CustomButton>
    </div>
  );
};

export default HomePage;

再びビルド・管理画面を起動し、作成されたボタンが表示されればOK!

スクリーンショット 2023-07-06 9.02.32.png

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?