使用Grunt为AngularJS配置不一样的环境变量

相信你也遇到过,开发环境中使用的接口地址与部署环境不一样,这样,每次build以前还须要手动修改,一点都不酷。不过,你能遇到的问题,别人也会遇到,伟大的Google总会给你答案。css

generator-env-config配合grunt-replace使用能够实现分开配置开发和生产环境。html

步骤以下:npm

  • 安装generator-env-configjson

    npm install generator-env-config
  • 生成开发环境的配置文件app

    yo env-config

    运行以后,在app平级目录生成config文件夹,下面environments下面会生成developement.json文件,内容以下:grunt

    {
      "foo": "bar"
    }

    里面的内容就是grunt-replace须要替换的键值对ui

  • 生成AngularJS配置文件code

    yo env-config:angular config

    运行以后,在config文件夹下生成config.js文件,内容以下cdn

    angular.module('services.config', [])
      .constant('configuration', {
        foo: '@@foo'
      });

    里面的内容能够自定义为不一样的变量,经过grunt-replace将@@替换成对应的值server

  • 安装grunt-replace

    npm install grunt-replace --save-dev
  • Gruntfile.js加载该任务

    grunt.loadNpmTasks('grunt-replace');
  • initConfig配置replace任务

    replace: {
      development: {
        options: {
          patterns: [{
            json: grunt.file.readJSON('./config/environments/development.json')
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['./config/config.js'],
          dest: '<%= yeoman.app %>/scripts/services/'
        }]
      }
    }
  • 生成configuration的constant

    grunt replace:development

    执行完后,app/scripts/services下面会生成一个config.js文件,内容为

    angular.module('services.config', [])
      .constant('configuration', {
        foo: 'bar'
      });
  • 将scripts/services/config.js引入index.html

  • app.js声明services.config依赖

    angular.module('environmentApp', ['services.config']);
  • 在controller、service中使用configuration

    angular.module('environmentApp')
      .controller('MainCtrl', function ($scope, configuration) {
        $scope.foo = configuration.foo;
      });
  • Gruntfile.js中的serve中添加replace任务

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'replace:development', // serve中添加
      'watch'
    ]);

上面是在开发环境中设置环境参数,若是要添加参数,只须要修改developement.json,并在config.js中声明此变量,运行grunt replace:development后,service下的config.js就会出现对应的值。

若是你想配置生产环境,只须要运行

yo env-config production

运行以后,config/environments下面会生成production.json,修改为生产环境的配置,在Gruntfile.js中build task中添加replace:production

grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'replace:production', //添加
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);
相关文章
相关标签/搜索