Configuration file in AngularJS

前端 未结 3 478
心在旅途
心在旅途 2020-12-07 11:05

What is the best way to create config file (Something like web config in .net), for storing urls, and other constants that may vary during the application deploy?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 11:33

    Use the .constant() method:

    angular.module('app').constant('MONGOLAB_CONFIG', {
      baseUrl: '/databases/',
      dbName: 'ascrum'
    });
    

    like in this example.

    Then you can just inject it where you need the constants.

    You can have different files defining different constants for development or production, and then use a tool like Grunt to use this or that file according to the environment.

    Let's assume you have this kind of folder structure:

    |-js/
    |  |-app.js
    |  |-anotherfile.js
    |  |-...
    |
    |-env/
    |  |-dev.js
    |  |-prod.js
    |
    |-index.html
    

    dev.js and prod.js defines the same .constant() service with different values. Then you can get the proper file to be concatenated with a gruntFile like that:

    grunt.registerTask('default', ['concat']);
    
    grunt.initConfig({
      env : process.env.NODE_ENV,
      src: {
        javascript: ['js/*.js'],
        config: ['env/<%= env %>.js']
      },
      concat: {
        javascript: {
          src:['<%= src.config %>', '<%= src.javascript %>'],
          dest:'myapp.js'
        }
      }
    });
    

    By running grunt you would get a myapp.js file containing the good constants.

    Edit: with Gulp you can do it like this:

    var paths = [
      'env/' + process.env.NODE_ENV + '.js',
      'js/**/*.js',
    ];
    
    var stream = gulp.src(paths)
      .pipe(plugins.concat('main.js'))
      .pipe(gulp.dest('/output'));
    

提交回复
热议问题