Web applications 基于grunt任务设置环境变量

Web applications 基于grunt任务设置环境变量,web-applications,ember.js,gruntjs,Web Applications,Ember.js,Gruntjs,我有一个webapp(emberjs),需要根据grunt任务设置env变量。因此,当我运行grunt服务器时,它会选择development,url将设置为localhost:5000。但当我执行grunt build时,它会选择production,url将设置为production.com 我的主要问题是,如何从ember读取这些变量。或者如何让grunt查找变量并根据任务更改它 有可能做那样的事吗?是的,有可能。使用来指定您的环境,并结合向应用程序代码公开环境变量之类的内容 根据您需要确

我有一个webapp(emberjs),需要根据grunt任务设置env变量。因此,当我运行
grunt服务器时,它会选择
development
,url将设置为
localhost:5000
。但当我执行
grunt build
时,它会选择
production
,url将设置为
production.com

我的主要问题是,如何从ember读取这些变量。或者如何让grunt查找变量并根据任务更改它

有可能做那样的事吗?

是的,有可能。使用来指定您的环境,并结合向应用程序代码公开环境变量之类的内容


根据您需要确保在Ember.js之前加载您的环境变量。

经过大量的谷歌搜索,没有好的示例,下面是我所做的

假设您通过
yo-ember
generator使用yeoman和scaffolding,并使用
grunt build
构建dist

Yo ember发电机v0.8使用grunt替换。升级到该版本。简而言之,我使用grunt替换将全局变量添加到index.html。这是怎么做的

将此脚本标记添加到app/index.html的combined-scripts.js块之前:

#app/index.html
<script>
  /*
    simplify grunt-replace strategy by placing env vars here.
  */
  window.MYCOMPANYCOM_ENV = {
    env: '@@env',
    apiHost: '@@apiHost'
  };
</script>

/* ADD THE ABOVE BEFORE THIS SECTION */
<!-- build:js(.tmp) scripts/main.js -->
<script src="scripts/combined-scripts.js"></script>
<!-- endbuild -->
现在,您的应用程序脚本可以访问app_config.json中定义的全局变量


我将不详细介绍,但这在开发中效果很好。对于
grunt build
,我将
replace:dist
步骤移到了构建步骤的末尾,并将index.html中的@ember变量替换为bower组件的路径。

我在emberjs之前设置了一个工作环境变量,而grunt ENV似乎很适合在那里定义变量。但是如何匹配grunt env变量以在我选择的位置进行设置呢。有没有像查找和替换这样的方法?在构建或运行服务器之前,如何将变量放置在特定位置?请参阅中的答案。根据我的回答,我建议你使用类似于将环境变量暴露到你的应用程序中的东西,但是如果你查看了,你会发现有更多的方法来剥这只猫的皮。
module.exports = function (grunt) {
  var appConfig = grunt.file.readJSON('app_config.json');

replace: {
  app: {
    options: {
      patterns: [
        {
          json: appConfig['app']
        }
      ]
    },
    files: [
      {src: '<%= yeoman.app %>/index.html', dest: '.tmp/index.html'}
    ]
  },
  dist: {
    options: {
      patterns: [
        {
          json: appConfig['dist']
        }
      ]
    },
    files: [
      {src: '<%= yeoman.dist %>/index.html', dest: '<%= yeoman.dist %>/index.html'}
    ]
  }
}
{
  "app": {
    "env": "development",
    "apiHost": "http://localhost:8080"
    },
  "dist": {
    "env": "dist",
    "apiHost": "/"
    }
}