如何将 env var 传递给 Docusaurus v2

din*_*ing 5 documentation command-line docusaurus

我一直在尝试让环境变量在我的文档构建中工作。
我在添加dotenv-webpack插件并以这种方式替换值方面取得了一些成功。这有需要某种.env文件的缺点

我想让我的构建自动知道环境变量,即。输出的一切printenv

我试过将它添加到 package.json: TEST_ENV_VAR=working docusaurus start" 但是当我记录process.env对象时,那里什么也没有。

我怎样才能使这项工作?

Ben*_*rth 9

构建时环境变量

两个步骤:

  • 跑步npm i --save-dev dotenv
  • 在您的 中docusaurus.config.js,只需添加:
require('dotenv').config()
Run Code Online (Sandbox Code Playgroud)
  • 确认您的.env目录包含环境变量,例如
ENVIRONMENT_VARIABLE_1=hello_there
Run Code Online (Sandbox Code Playgroud)

您的.env文件将被加载,您process.env.ENVIRONMENT_VARIABLE_1现在就可以使用。

运行时环境变量:

process.env例如,要在 React 组件中使用变量,请执行上面的内置环境变量步骤,然后使用customFieldsdocusaurus 配置对象的字段:

const config = {
  ...
  customFields: {
    'ENVIRONMENT_VARIABLE_1': process.env.ENVIRONMENT_VARIABLE_1,
    'ENVIRONMENT_VARIABLE_2': process.env.ENVIRONMENT_VARIABLE_2,
  },
  ...
}
Run Code Online (Sandbox Code Playgroud)

在我的打字稿组件中,通过以下方式访问它们:

const {siteConfig} = useDocusaurusContext();

  return <div>{`${siteConfig.ENVIRONMENT_VARIABLE_1}`}</div>;
Run Code Online (Sandbox Code Playgroud)

请阅读docusaurus 文档中的自定义配置以获取更多信息。

评论

乔尼·纳伯斯的答案(和包裹)对我来说是不必要的,实际上让我感到困惑。如果您希望构建过程使用环境变量,请使用本周已下载 2200 万次的极其流行的 npm 软件包(dotenv ) ,而不是他的软件包(docusaurus2-dotenv),后者对我不起作用。

如果您需要在运行时使用环境变量,同时避免像我上面那样将其添加到配置对象,也许他的包更有用?不过,既然如此,我还找到了另一种解决办法,那就是使用以.开头的环境变量REACT_APP_


Jon*_*ors 7

I created a plugin that adds the functionality of dotenv-webpack to Docusaurus2's webpack config.

https://www.npmjs.com/package/docusaurus2-dotenv

You should be able to npm install docusaurus2-dotenv, enable systemvar, and add it to your plugin section and your systemvar values will be accessible e.g. process.env.PATH.

This would allow you to make use of .env files (if you decide want to use them in the future), as well as any environment variables that get created during CI or that exist on the machine that is building the code.

docusaurus.config.js

module.exports = {
  ..., // other docusaurus2 config
  plugins: [
    [
      "docusaurus2-dotenv",
      {
        systemvars: true,
      },
    ],
  ],
}

Run Code Online (Sandbox Code Playgroud)