我正在尝试在AngularJS中使用环境变量来进行特定于环境的配置。我正在使用使用Grunt的Yeoman工作流,并且grunt-ng-constant插件据称可以帮助进行特定于环境的配置。在遵循此tutorial之后,我会相应地设置我的Gruntfile,但是当我在控制台中运行grunt serve时,config.js不会写入/app/scripts/。没有config.js,我无法将环境变量注入(inject) Angular 应用程序。

这是我的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/.tmp与Gruntfile在同一目录(client)中。

我的应用程序文件结构:

javascript - grunt-ng-constant不产生配置脚本-LMLPHP

最佳答案

没有调用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'
}

09-30 13:06