【问题标题】:How do I access environment variables in Strapi v4?如何访问 Strapi v4 中的环境变量?
【发布时间】:2022-11-20 15:31:21
【问题描述】:
  • Strapi版本:4.3.0
  • 操作系统: Ubuntu 20.04
  • 数据库: SQLite
  • 节点版本: 16.16
  • NPM 版本:8.11.0
  • 纱版: 1.22.19

我为文章集合类型创建了Preview button。我正在使用 Strapi 博客模板。我设法使预览按钮出现在内容管理者.当您单击“预览”按钮时,我硬编码了要打开的链接并且它有效。现在,我希望插件使用链接环境变量而不是硬编码链接。我不知道如何访问插件源代码中的环境变量。

我的目标:

我想更换

href={`http://localhost:3000?secret=abc&slug=${initialData.slug}`}

href={${CLIENT_FRONTEND_URL}?secret=${CLIENT_SECRET}&slug=${initialData.slug}`}

./src/plugins/previewbtn/admin/src/components/PreviewLink/index.js

其中 CLIENT_FRONTEND_URLCLIENT_SECRET 是像这样声明的环境变量.env:

CLIENT_FRONTEND_URL=http://localhost:3000
CLIENT_PREVIEW_SECRET=abc

这是我使用的代码的概要:

首先,我使用博客模板创建了一个 strapi 应用程序,然后创建了一个插件。

// Create strapi app named backend with a blog template
 $  yarn create strapi-app backend  --quickstart --template @strapi/template-blog@1.0.0 blog && cd backend

// Create plugin
$ yarn strapi generate

接下来,我创建了一个 PreviewLink 文件来为预览按钮提供一个链接

// ./src/plugins/previewbtn/admin/src/components/PreviewLink/index.js
import React from 'react';
import { useCMEditViewDataManager } from '@strapi/helper-plugin';
import Eye from '@strapi/icons/Eye';
import { LinkButton } from '@strapi/design-system/LinkButton';

const PreviewLink = () => {
  const {initialData} = useCMEditViewDataManager();
  if (!initialData.slug) {
    return null;
  }

  return (
    <LinkButton
      size="S"
      startIcon={<Eye/>}
      style={{width: '100%'}}
      href={`http://localhost:3000?secret=abc&slug=${initialData.slug}`}
      variant="secondary"
      target="_blank"
      rel="noopener noreferrer"
      title="page preview"
    >Preview
    </LinkButton>
  );
};

export default PreviewLink;

然后我只在 bootstrap(app) { ... } 部分编辑了这个预生成的文件

// ./src/plugins/previewbtn/admin/src/index.js
import { prefixPluginTranslations } from '@strapi/helper-plugin';
import pluginPkg from '../../package.json';
import pluginId from './pluginId';
import Initializer from './components/Initializer';
import PreviewLink from './components/PreviewLink';
import PluginIcon from './components/PluginIcon';

const name = pluginPkg.strapi.name;
export default {
  register(app) {
    app.addMenuLink({
      to: `/plugins/${pluginId}`,
      icon: PluginIcon,
      intlLabel: {
        id: `${pluginId}.plugin.name`,
        defaultMessage: name,
      },
      Component: async () => {
        const component = await import(/* webpackChunkName: "[request]" */ './pages/App');
        return component;
      },

      permissions: [
        // Uncomment to set the permissions of the plugin here
        // {
        //   action: '', // the action name should be plugin::plugin-name.actionType
        //   subject: null,
        // },
      ],
    });

    app.registerPlugin({
      id: pluginId,
      initializer: Initializer,
      isReady: false,
      name,
    });
  },

  bootstrap(app) {
    app.injectContentManagerComponent('editView', 'right-links', {
      name: 'preview-link',
      Component: PreviewLink
    });
  },

  async registerTrads({ locales }) {
    const importedTrads = await Promise.all(
      locales.map(locale => {
        return import(
          /* webpackChunkName: "translation-[request]" */ `./translations/${locale}.json`
        )

          .then(({ default: data }) => {
            return {
              data: prefixPluginTranslations(data, pluginId),
              locale,
            };
          })

          .catch(() => {
            return {
              data: {},
              locale,
            };
          });
      })
    );
    return Promise.resolve(importedTrads);
  },
};

最后,这创建了这个文件来启用插件Reference

// ./config/plugins.js
module.exports = {
    // ...
    'preview-btn': {
      enabled: true,
      resolve: './src/plugins/previewbtn' // path to plugin folder
    },
    // ...
  }


【问题讨论】:

    标签: javascript reactjs plugins environment-variables strapi


    【解决方案1】:

    我通过添加一个解决了这个问题自定义 webpack 配置使 Strapi 的管理前端能够将环境变量作为全局变量访问。

    我改名了./src/admin/webpack.example.config.js./src/admin/webpack.config.js.请参阅官方 Strapi v4 文档中的 v4 code migration: Updating the webpack configuration

    然后,在官方 webpack 文档的帮助下,我插入了以下代码:DefinePlugin | webpack

    // ./src/admin/webpack.config.js
    'use strict';
    
    /* eslint-disable no-unused-vars */
    module.exports = (config, webpack) => {
      // Note: we provide webpack above so you should not `require` it
      // Perform customizations to webpack config
      // Important: return the modified config
      config.plugins.push(
        new webpack.DefinePlugin({
          CLIENT_FRONTEND_URL: JSON.stringify(process.env.CLIENT_FRONTEND_URL),
          CLIENT_PREVIEW_SECRET: JSON.stringify(process.env.CLIENT_PREVIEW_SECRET),
        })
      )
    
      return config;
    };
    

    之后我重建了我的应用程序并且它有效。

    【讨论】:

      【解决方案2】:

      您不必更改 webpack 配置,只需在根目录中找到 .env 文件 添加

      AWS_ACCESS_KEY_ID = your key here
      

      然后只需导入 accessKeyId: env('AWS_ACCESS_KEY_ID')

      【讨论】:

        猜你喜欢
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        • 1970-01-01
        相关资源
        最近更新 更多