I'm trying to configure my JS build to do next:
I'm using a JS variable to define the application root:
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
};
});
During local development I'm using code without Grunt build and running Grunt only for test & production builds.
Grunt is running from the Maven plugin using command-line configuration. So it is the only way to pass the environment variable.
pom.xml
<plugin>
<groupId>pl.allegro</groupId>
<artifactId>grunt-maven-plugin</artifactId>
<configuration>
<gruntOptions>
<gruntOption>--verbose</gruntOption>
</gruntOptions>
<target>build</target>
</configuration>
</plugin>
Grunt configuration is pretty simple and looks like this:
Gruntfile.js
grunt.registerTask('build', [
'karma',
'requirejs',
'concat',
'csso',
'copy',
'processhtml'
]);
The question:
How can I configure Grunt to change my variable in next way?
- Default value of
mainRoot
should behttp://localhost:3000
- Environment variable should be set via command-line from the Maven plugin
- When running Grunt with
PROD
environment -mainRoot
should be changed tohttp://myapp.com
- When running Grunt with
TEST
environment -mainRoot
should be changed tohttp://myapp-test.com
Thank you!
I find a combination of
grunt-replace
andgrunt-config
works well.In your
Gruntfile.js
, configuregrunt-config
like this (see the README):In your
globals.js
, create an@@
placeholder forgrunt-replace
to find and replace:In your
Gruntfile.js
, configuregrunt-replace
like this:Then create a command-line option such as
--env
, which will acceptlocal
ortest
orprod
, and will default tolocal
if omitted:and update your
build
task to useconfig
andreplace
:Now you can run Grunt from the command-line with the new
--env
option: