Отображение пользовательских плагинов (страниц) в левом меню в Strapi 3

Strapi 3.0.0 теперь находится в версии Betaa, и они сильно изменились по сравнению с предыдущей версией (Alpha) Но теперь настройка панели администратора больше не понятна в бета-версии, структура была изменена и нет никаких инструкций о том, как редактировать админ-панель и настраивать ее (хотя они говорят, что она «ПОЛНОСТЬЮ» настраивается), что на самом деле не соответствует действительности.

Итак, мой вопрос: как создать плагин, к которому можно будет получить доступ с левой боковой панели (рядом с Content Manager ... и т. Д.), Поскольку теперь кажется, что если вы поместите интерфейс вашего плагина внутрь /plugins/my-plugin/admin/src, он проигнорирует.

Спасибо.


person Sletheren    schedule 29.09.2019    source источник


Ответы (2)


Чтобы отобразить плагин в панели администрирования, необходимо выполнить несколько требований:

1.Структура файлов:

Папка администратора вашего плагина должна иметь следующую структуру

./admin
  - src
    - containers
      - App
        index.js
      - Initializer
        index.js
    - translations
      - en.json
      - index.js
    - index.js
    - lifecycles.js
    - pluginId.js

Вот содержание каждого файла


Путь: контейнеры / App / index.js

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import { NotFound } from 'strapi-helper-plugin';
// Utils
import pluginId from '../../pluginId';
// Containers
import HomePage from '../HomePage';

const App = () => {
  return (
    <div className={pluginId}>
      <Switch>
        <Route path={`/plugins/${pluginId}`} component={HomePage} exact />
        <Route component={NotFound} />
      </Switch>
    </div>
  );
};

export default App;

Путь: контейнеры / Initializer / index.js

import { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import pluginId from '../../pluginId';

const Initializer = ({ updatePlugin }) => {
  const ref = useRef();
  ref.current = updatePlugin;

  useEffect(() => {
    ref.current(pluginId, 'isReady', true);
  }, []);

  return null;
};

Initializer.propTypes = {
  updatePlugin: PropTypes.func.isRequired,
};

export default Initializer;

Путь: translations / index.js

import en from './en.json';
import fr from './fr.json';
// import the others translations if needed

const trads = {
  en,
  fr,
};

export default trads;

Путь: index.js

import React from 'react';
import pluginPkg from '../../package.json';
import pluginId from './pluginId';
import App from './containers/App';
import Initializer from './containers/Initializer';
import lifecycles from './lifecycles';
import trads from './translations';

const pluginDescription = pluginPkg.strapi.description || pluginPkg.description;

function Comp(props) {
  return <App {...props} />;
}

const plugin = {
  blockerComponent: null,
  blockerComponentProps: {},
  description: pluginDescription,
  icon: pluginPkg.strapi.icon,
  id: pluginId,
  initializer: Initializer,
  injectedComponents: [],
  isReady: false,
  layout: null,
  lifecycles,
  leftMenuLinks: [],
  leftMenuSections: [],
  mainComponent: Comp,
  name: pluginPkg.strapi.name,
  preventComponentRendering: false,
  trads,
};

export default plugin;

Путь: pluginId.js

const pluginPkg = require('../../package.json');
const pluginId = pluginPkg.name.replace(
  /^strapi-plugin-/i,
  ''
);

module.exports = pluginId;

Путь: lifecycles.js

function lifecycles() {}

export default lifecycles;

Как только ваш плагин соответствует требованиям, вы можете изменить основной пакет для его рендеринга.

2. Выполните рендеринг вашего плагина.

Создайте файл my-app/admin/src/plugins.js

В этом файле вам потребуются плагины по умолчанию для вашего приложения (те, что находятся в node_modules).

const injectReducer = require('./utils/injectReducer').default;
const useInjectReducer = require('./utils/injectReducer').useInjectReducer;
const injectSaga = require('./utils/injectSaga').default;
const useInjectSaga = require('./utils/injectSaga').useInjectSaga;
const { languages } = require('./i18n');

window.strapi = Object.assign(window.strapi || {}, {
  node: MODE || 'host',
  env: NODE_ENV,
  backendURL: BACKEND_URL === '/' ? window.location.origin : BACKEND_URL,
  languages,
  currentLanguage:
    window.localStorage.getItem('strapi-admin-language') ||
    window.navigator.language ||
    window.navigator.userLanguage ||
    'en',
  injectReducer,
  injectSaga,
  useInjectReducer,
  useInjectSaga,
});

module.exports = {
  'strapi-plugin-users-permissions': require('../../plugins/strapi-plugin-users-permissions/admin/src')
    .default,
  // Add the other plugins here
  // ...,
  // Add your newly created plugin here (the path is different than the others)
  'my-plugin': require('../../../plugins/my-plugin/admin/src').default,
};
person soupette    schedule 10.10.2019

Я не знаю, решили ли вы свою проблему, но поскольку я боролся с той же проблемой при миграции, я сделал небольшое репо, чтобы лучше понять, как работают новые плагины:

https://github.com/lambertkevin/strapi-v3-beta-plugin-poc

Надеюсь, это поможет

изменить: забыл упомянуть, что все, что вам нужно знать, объясняется в readme

person Chop    schedule 21.10.2019