2015-11-10 37 views
2

我想在我的AngularJS中使用環境變量來執行環境特定的配置。我使用的是使用Grunt的Yeoman工作流程,grunt-ng-constant插件旨在幫助進行特定於環境的配置。在跟着這個tutorial,我相應地設置了我的Gruntfile,但是當我在控制檯中運行grunt serve時,config.js沒有寫入/app/scripts/。沒有config.js,我不能將環境變量注入到角度應用程序中。grunt-ng-constant不生成配置腳本

這裏是我的Gruntfile片段:

module.exports = function (grunt) { 

    // Time how long tasks take. Can help when optimizing build times 
    require('time-grunt')(grunt); 

    // Automatically load required Grunt tasks 
    require('jit-grunt')(grunt, { 
    useminPrepare: 'grunt-usemin', 
    ngtemplates: 'grunt-angular-templates', 
    cdnify: 'grunt-google-cdn' 
    }); 

    // Configurable paths for the application 
    var appConfig = { 
    app: require('./bower.json').appPath || 'app', 
    dist: '../server/dist' 
    }; 

    grunt.loadNpmTasks('grunt-contrib-clean'); 
    grunt.loadNpmTasks('grunt-contrib-jshint'); 
    grunt.loadNpmTasks('grunt-ng-constant'); 

    // Define the configuration for all the tasks 
    grunt.initConfig({ 

    // Project settings 
    yeoman: appConfig, 

    ngconstant: { 
     // options for all environments 
     options: { 
     space: ' ', 
     wrap: '"use strict";\n\n {%= __ngModule %}', 
     name: 'config' 
     }, 

     // Development/Testing environment 
     development: { 
     options: { 
      dest: '<%= yeoman.app %>/scripts/config.js' 
     }, 
     constants: { 
      ENV: { 
      name: 'development', 
      apiEndpoint: 'http://localhost:3000' 
      } 
     } 
     }, 

     // Production environment 
     production: { 
     options: { 
      dest: '<%= yeoman.dist %>/scripts/config.js' 
     }, 
     constants: { 
      ENV: { 
      name: 'production', 
      apiEndpoint: 'http://productionUrl' 
      } 
     } 
     } 
    }, 

    ... 

    grunt.registerTask('serve', 'Compile then start a connect web server',   function (target) { 
     if (target === 'dist') { 
      return grunt.task.run(['build', 'connect:dist:keepalive']); 
     } 

     grunt.task.run([ 
      'clean:server', 
      'wiredep', 
      'concurrent:server', 
      'autoprefixer:server', 
      'connect:livereload', 
      'watch', 
      'ngconstant:development' 
     ]); 
    }); 

    ... 

產生什麼是/.sass-cache並在同一目錄下(client)作爲Gruntfile /.tmp

我的應用程序文件結構:

enter image description here

+1

招行'「ngconstant:development''旁邊'」 autoprefixer:服務器」,'所以它是連接前&觀看任務。不要忘記添加一個逗號!然後,通過更改appConfig來修改您的應用的路徑,使其看起來像[this](http://pastebin.ubuntu.com/13220494/)。 – Lucio

+0

做了什麼? – Lucio

+0

@Lucio是的,你的解決方案工作。謝謝! – photon

回答

1

ngconstant任務不會被調用,因爲它是watch任務之後。修改運行塊,使行'ngconstant:development'旁邊'autoprefixer:server',所以它是在連接&觀看任務之前。不要忘記添加一個逗號!

grunt.task.run([ 
     'clean:server', 
     'wiredep', 
     'concurrent:server', 
     'autoprefixer:server', 
     'ngconstant:development', 
     'connect:livereload', 
     'watch' 
    ]); 

此外,應用程序路徑可能在bower.json文件中是錯誤的。可以肯定,通過改變appConfig將路徑修改爲您的應用程序,所以它看起來像這樣:

var appConfig = { 
    app: 'app', 
    dist: '../server/dist' 
}