如何在运行浏览器脚本之前设置process.env? [英] How to set process.env before a browserified script is run?

查看:807
本文介绍了如何在运行浏览器脚本之前设置process.env?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初的 html 来自后端。服务器具有定义的 process.env.NODE_ENV (以及其他环境变量)。浏览器代码可以构建一次,并在多个环境中运行分段生产等),因此无法将环境变量内联到浏览器化的脚本中(例如,通过 envify )。我希望能够在呈现的html中写出环境变量,并让浏览器化的代码使用这些变量。

The initial html comes from the back-end. The server has a defined process.env.NODE_ENV (as well as other environment variables). The browserified code is built once and runs on multiple environments (staging, production, etc.), so it isn't possible to inline the environment variables into the browserified script (via envify for example). I'd like to be able to write out the environment variables in the rendered html and for browserified code to use those variables. Is that possible?

这是我想像的那样:

<html>
  <head>
    <script>window.process = {env: {NODE_ENV: 'production'}};</script>
    <script src="/build/browserified_app.js"></script>
  </head>
</html>


推荐答案

而不是在此处和此处对环境变量进行硬编码,请使用加密插件。

Instead of hardcoding enviroment variables here and there, use the envify plugin.

npm install envify 

此插件会自动修改 process.env。 VARIABLE_HERE 以及您作为环境变量传递的内容。

This plugin automatically modifies the process.env.VARIABLE_HERE with what you passed as an argument to envify.

例如:

browserify index.js -t [ envify --DEBUG app:* --NODE_ENV production --FOO bar ] > bundle.js

在您的应用程序中 process.env.DEBUG 将替换为 app:* process.env.NODE_ENV 将替换为生产,依此类推。这是干净的&&我认为这是一种优雅的方式。

In your application process.env.DEBUG will be replaced by app:*, process.env.NODE_ENV will be replaced by production and so on. This is a clean && elegant way in my opinion to deal with this.

这篇关于如何在运行浏览器脚本之前设置process.env?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆