使用Grunt为不同的环境更改JS变量

时间:2015-06-12 07:18:52

标签: javascript build gruntjs environment-variables

我正在尝试配置我的JS版本来做下一步:

我正在使用JS变量来定义应用程序根目录:

globals.js

define(function (require) {
   "use strict";
   return {
      mainRoot: "http://myapp.com"
      //mainRoot: "http://localhost:3000" - local run
      //mainRoot: "http://myapp-test.com" - test server
   };
});

在本地开发期间,我使用的代码没有Grunt构建,只运行Grunt用于测试&生产建设。

Grunt使用命令行配置从Maven插件运行。所以这是传递环境变量的唯一方法。

的pom.xml

<plugin>
    <groupId>pl.allegro</groupId>
    <artifactId>grunt-maven-plugin</artifactId>
    <configuration>
        <gruntOptions>
            <gruntOption>--verbose</gruntOption>
        </gruntOptions>
        <target>build</target>
    </configuration>
</plugin>

Grunt配置非常简单,如下所示:

Gruntfile.js

grunt.registerTask('build', [
    'karma',
    'requirejs',
    'concat',
    'csso',
    'copy',
    'processhtml'
]);

问题:

如何配置Grunt以下一种方式更改我的变量?

  1. mainRoot的默认值应为http://localhost:3000
  2. 应该通过Maven插件的命令行设置环境变量
  3. PROD环境中运行Grunt时,mainRoot应更改为http://myapp.com
  4. TEST环境中运行Grunt时,mainRoot应更改为http://myapp-test.com
  5. 谢谢!

1 个答案:

答案 0 :(得分:10)

我发现grunt-replacegrunt-config的组合效果很好。

Gruntfile.js中,像这样配置grunt-config(请参阅README):

config: {
    local: {
        options: {
            variables: {
                mainroot: 'http://localhost:3000'
            }
        }
    },
    test: {
        options: {
            variables: {
                mainroot: 'http://myapp-test.com'
            }
        }
    },
    prod: {
        options: {
            variables: {
                mainroot: 'http://myapp.com'
            }
        }
    }
}

globals.js中,为grunt-replace创建an @@ placeholder以查找和替换:

define(function (require) {
   "use strict";
   return {
      mainRoot: "@@MAINROOT"
   };
});

Gruntfile.js中,像这样配置grunt-replace

replace: {
    my_target: {
        options: {
            patterns: [
                {
                    match: 'MAINROOT',
                    replacement: '<%= grunt.config.get("mainroot") %>'
                }
            ]
        },
        src: ... ,
        dest: ...
    }
}

然后创建一个command-line option,例如--env,它将接受localtestprod,默认为local省略:

var envTarget = grunt.option('env') || 'local';

并更新您的build任务以使用configreplace

grunt.registerTask('build', [
    'config:' + envTarget,
    'replace',
    'karma',
    'requirejs',
    'concat',
    'csso',
    'copy',
    'processhtml'
]);

现在,您可以使用新的--env选项从命令行运行Grunt:

grunt build --env=local
grunt build --env=test
grunt build --env=prod
相关问题