根据grunt任务设置Env变量

时间:2013-08-16 10:58:56

标签: web-applications ember.js gruntjs

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

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

是否可以做类似的事情?

2 个答案:

答案 0 :(得分:2)

是的,这是可能的。使用grunt-env结合类似grunt-usemin的内容指定您的环境,以将您的环境变量公开给您的应用程序代码。

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

答案 1 :(得分:1)

经过大量的谷歌搜索,没有好的例子,这就是我所做的。

假设您使用yo ember生成器的脚手架并使用grunt build来构建dist。

Yo ember-generator v0.8使用grunt-replace。升级到该版本。简而言之,我使用grunt-replace将全局变量添加到index.html。这是怎么回事。

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

#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 -->

将Gruntfile.js中的replace配置更改为:

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_config.json

创建一个新文件
{
  "app": {
    "env": "development",
    "apiHost": "http://localhost:8080"
    },
  "dist": {
    "env": "dist",
    "apiHost": "/"
    }
}

现在,您的应用脚本可以访问app_config.json中定义的全局变量。

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