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

Changing JS variable with Grunt for different environments

我正在尝试配置我的 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. 当 运行 Grunt 与 PROD 环境时 - mainRoot 应更改为 http://myapp.com
  4. 当 运行 Grunt 使用 TEST 环境时 - mainRoot 应更改为 http://myapp-test.com

谢谢!

我发现 grunt-replace and grunt-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 选项从命令行 运行 G运行t:

grunt build --env=local
grunt build --env=test
grunt build --env=prod