您如何在 HTML <script src="" 中引用 process.env 变量?反应

How do you reference a process.env variable in HTML <script src="" ? React

我有一个 React 应用程序,正在使用 dotenv-webpack 来管理我的 API 密钥。

我有: - 使用 API 键创建了一个 .env 并忽略了它。 - 在 webpack.config.js.

中需要并添加了 dotenv 作为插件

之后,我可以使用 process.env.api_key 引用 .js 文件中的其中一个键。但是我在尝试在脚本标记的 index.html 中引用它时遇到问题。

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/style/style.css">
    <link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
    <script src="https://maps.googleapis.com/maps/api/js?key=process.env.GOOGLEMAP_API_KEY"></script>
  </head>
  <body>
    <div class="container"></div>
  </body>
  <script src="/bundle.js"></script>
</html>

如何在此处引用 process.env.API_key?

<script src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]"></script>

我试过在 .js 文件中使用反引号,例如 ${API_KEY},但在 .html 文件中不起作用。

解决方案

您不能直接在 html 中引用 process.env 变量。

index.html 创建您自己的模板并将 api url 替换为参数。

HtmlWebpackPlugin

Simplifies creation of HTML files to serve your webpack bundles.

您可以让插件为您生成一个 HTML 文件,使用 lodash 模板提供您自己的模板或使用您自己的加载器。

Webpack.config.js

HtmlWebpackPlugin 允许您创建参数并将其传递给您的模板:

   const api_key = process.env.api_key;
   const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: 'index.js',
      plugins: [
        new HtmlWebpackPlugin({
          inject: false,
          template: './template.html',

          // Pass the full url with the key!
          apiUrl: `https://maps.googleapis.com/maps/api/js?key=${api_key}`,

        });
      ]
    }

template.html

在模板中您可以访问参数:

<script src="<%= htmlWebpackPlugin.options.apiUrl %>"></script>

参见:Writing Your Own Templates

备注

This is a modified answer from this comment, please read the full conversation.

I put the following code in componentWillMount where the map renders and it worked (at least in development: const API_KEY = process.env.GOOGLEMAP_API_KEY; const script = document.createElement('script'); script.src = https://maps.googleapis.com/maps/api/js?key=${API_KEY}; document.head.append(script);

我能够使用 bigmugcup 在上面的评论中发布的代码来实现它。我没有修改 webpack.config.js 文件。

如果您已经在使用 create-react-app,则更新至

即可使用
<script src="https://maps.googleapis.com/maps/api/js?key=%REACT_APP_API_KEY%"></script>

the docs

中所述

You can also access the environment variables starting with REACT_APP_ in the public/index.html.

您可以使用的简单方法

在HTML

<p>%NODE_ENV%</p>

在脚本中

<script>
if('%NODE_ENV%' === 'production') {
.... some code
}
</script>