Igo*_*nov 2 javascript build environment-variables gruntjs
我正在尝试配置我的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
};
});
Run Code Online (Sandbox Code Playgroud)
在本地开发期间,我使用的代码没有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>
Run Code Online (Sandbox Code Playgroud)
Grunt配置非常简单,看起来像这样:
Gruntfile.js
grunt.registerTask('build', [
'karma',
'requirejs',
'concat',
'csso',
'copy',
'processhtml'
]);
Run Code Online (Sandbox Code Playgroud)
问题:
如何配置Grunt以下一种方式更改我的变量?
mainRoot应该是http://localhost:3000PROD环境中运行Grunt时- mainRoot应该更改为 http://myapp.comTEST环境中运行Grunt时- mainRoot应该更改为 http://myapp-test.com谢谢!
Tac*_*tex 10
我找到了一个组合grunt-replace并grunt-config运作良好.
在你的Gruntfile.js配置中,grunt-config这样配置(参见自述文件):
config: {
local: {
options: {
variables: {
mainroot: 'http://localhost:3000'
}
}
},
test: {
options: {
variables: {
mainroot: 'http://myapp-test.com'
}
}
},
prod: {
options: {
variables: {
mainroot: 'http://myapp.com'
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在你globals.js创建一个@@占位符,用于grunt-replace查找和替换:
define(function (require) {
"use strict";
return {
mainRoot: "@@MAINROOT"
};
});
Run Code Online (Sandbox Code Playgroud)
在你的Gruntfile.js,配置grunt-replace如下:
replace: {
my_target: {
options: {
patterns: [
{
match: 'MAINROOT',
replacement: '<%= grunt.config.get("mainroot") %>'
}
]
},
src: ... ,
dest: ...
}
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个命令行选项,例如--env,它将接受local或test或prod,local如果省略则默认为:
var envTarget = grunt.option('env') || 'local';
Run Code Online (Sandbox Code Playgroud)
并更新您的build任务以使用config和replace:
grunt.registerTask('build', [
'config:' + envTarget,
'replace',
'karma',
'requirejs',
'concat',
'csso',
'copy',
'processhtml'
]);
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用新--env选项从命令行运行Grunt :
grunt build --env=local
grunt build --env=test
grunt build --env=prod
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2145 次 |
| 最近记录: |