我在使用Gruntjs构建的项目中使用Restangular.这是一个片段:
// scripts/app.js
angular.module('myApp',['restangular'])])
.config(['RestangularProvider',function(RestangularProvider) {
/* this is different on dev,test,prod environments */
var baseUrl = 'http://localhost:8080/sms-api/rest/management/';
RestangularProvider.setBaseUrl(baseUrl);
}])
如果在cli中指定了baseUrl,或者如果未指定,则希望使用默认值:
$grunt server Using default value for 'baseUrl' $grunt build --rest.baseUrl='http://my.domain.com/rest/management/' Using 'http://my.domain.com/rest/management/' for 'baseUrl'
我怎样才能做到这一点?
借助于
Grunt preprocess可以在文件中替换(和其他东西)模板是有用的.
首先将其添加到您的.js代码中:
/* Begin insertion of baseUrl by GruntJs */ /* @ifdef baseUrl var baseUrl = /* @echo baseUrl */ // @echo ";" // @endif */ /* @ifndef baseUrl var baseUrl = 'http://www.fallback.url'; // @endif */ /* End of baseUrl insertion */
然后在grunt文件中,安装grunt预处理(即npm安装grunt-preprocess –save-dev后,添加以下配置:
preprocess: {
options: {
context: {
}
},js: {
src: 'public/js/services.js',dest: 'services.js'
}
},
显然,您需要根据您使用的任何文件来更新js文件列表.重要通知 – 如果您计划更新同一个文件(而不是新目的地),则需要使用内联选项
最后,为了使用命令行配置变量,请将以下自定义任务添加到grunt文件中:
grunt.registerTask('baseUrl',function () {
var target = grunt.option('rest.baseUrl') || undefined;
grunt.log.ok('baseUrl is set to',target);
grunt.config('preprocess.options.context.baseUrl',target);
grunt.task.run('preprocess');
});
最后,运行baseUrl任务,如下所示:
grunt baseUrl --rest.baseUrl='http://some.domain.net/public/whatever'
注意我放在一个后备的url,所以你也可以运行grunt baseUrl和咕噜将您的baseUrl设置为您定义的.