首页 文章

如何在HTML <script src =“”中引用process.env变量?应对

提问于
浏览
8

我有一个反应应用程序,并使用dotenv-webpack来管理我的API密钥 .

我有: - 使用API密钥创建一个.env并对其进行gitignored . - 需要并添加dotenv作为webpack.config.js中的插件 .

之后,我已经能够使用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文件中不起作用 .

2 回答

  • 0

    我将以下代码放在componentWillMount中, Map 呈现并且它起作用(至少在开发中:const API_KEY = process.env.GOOGLEMAP_API_KEY; const script = document.createElement('script'); script.src = https:// maps.googleapis.com/maps/api/js?key=$ ; document.head.append(script);

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

  • 2

    解决方案

    您无法直接在 html 中引用 process.env 变量 .

    index.html 创建自己的模板,并用参数替换api url .

    HtmlWebpackPlugin

    简化HTML文件的创建,以便为您的webpack包提供服务 .

    您可以让插件为您生成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

    注意事项

    这是此评论的修改后的答案,请阅读完整的对话 .

相关问题