Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用env变量将内联脚本插入index.html_Reactjs_Webpack_Environment Variables_Inline Scripting - Fatal编程技术网

Reactjs 使用env变量将内联脚本插入index.html

Reactjs 使用env变量将内联脚本插入index.html,reactjs,webpack,environment-variables,inline-scripting,Reactjs,Webpack,Environment Variables,Inline Scripting,我想在index.html中加载hotjar跟踪代码(仅内联脚本),但这取决于env变量。 我尝试使用webpack DefinePlugin new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), }), 得到这个env,但我只能从react组件得到它 componentWillMount() { const env = process.e

我想在index.html中加载hotjar跟踪代码(仅内联脚本),但这取决于env变量。 我尝试使用webpack DefinePlugin

new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    }),
得到这个env,但我只能从react组件得到它

componentWillMount() {
    const env = process.env.NODE_ENV;
    document.getElementById('hotjar').innerHTML = env === 'production' ? "...script1" : "...script2" 
  }
然后我使用'innerHTML'将脚本放到index.html中,但它并没有像我预期的那样工作

下面是index.html的主体

<body>
 <div id="root"></div>
  <script src="/dist/bundle.js"></script>
  <script id="hotjar">
  </script>
</body>

所以,我需要在index.html或类似的脚本中获取它? 有人能帮我吗?
谢谢。

您可以为每个环境使用不同的文件。像
tracking\u test.js
tracking\u prod.js
一样,在构建时使用webpack选择合适的文件,并将其重命名为
tracking.js
。请参阅html文件中的
tracking.js
。通过这种方式,您不需要发送不必要的代码


如果您想继续修改innerHTML路由,请查看它们是否有更好的API。

“env variable”,“获取此env,但我只能从react组件获取”,这是什么,请澄清?什么站台?请提供您尝试过的东西,以便我们能够帮助修复它,而不是简单地“我尝试了几件事”和“我不确定该做什么”。“hotjar跟踪代码”-什么代码,我们看不到任何代码。也许现在更好,这里也有很多信息,谢谢!最后一个问题是我只需要使用内联脚本