B
B
bromzh2015-07-08 02:13:00
JavaScript
bromzh, 2015-07-08 02:13:00

What is the best way to organize local settings in an angular project?

The project develops a server part in the form of an API, to which an angular project is attached. In the local version, for example, you need to specify 1 path to the api, in production another.
For the frontend, I want to have:

  • a file with default values, which is included in the turnip and which stores all the project settings.
  • a file with local settings that is not tracked by git, but if it exists, then the default settings are replaced with the settings from this file.

How it is better to implement it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
bromzh, 2015-07-08
@bromzh

Thanks for the replies, they led me to a solution. I did this: I
took the project structure generated by generator-gulp-angular as a basis.
At the root, I created the config folder, which contains json files with settings. The default.json describes all kinds of settings. In other files, you just need to redefine the desired field:

// config/default.json
{
  "api": {
    "scheme": "http",
    "host": "localhost",
    "port": 8080,
    "root": "/api/v1/"
  }
}
// config/prod.json
{
  "api": {
    "host": "example.com"
  }
}
// config/dev.json
{}

The local.json file has been added to gitignor, but it can be used (if it exists).
Next, I wrote a task for gulp, which, depending on the environment, generates a js file with an angular module using gulp-ng-config:
// gulp/config.js
'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var cjson = require('cjson');
var b2v = require('buffer-to-vinyl');
var gulpNgConfig = require('gulp-ng-config');

module.exports = function (options) {
  function p(name) {
    return [options.config + '/default.json', options.config + '/' + name + '.json'];
  }

  gulp.task('config', function () {
    var env = gutil.env.env || 'dev'; // получаем имя окружения через значение аргумента командной строки, или выставляем его равным dev, если ничего не передавалось
    var config = JSON.stringify({
      config: cjson.load(p([env]), true) // Загружаем json'ы, сливая их в 1 объект
    });

    return b2v.stream(new Buffer(config), 'config.js') // создаём поток из строки
      .pipe(gulpNgConfig('lemonfront.config', { // генерим по JSON'у ангуляровский модуль
        createModule: false
      }))
      .pipe(gulp.dest(options.tmp + '/serve/app/')); // и записываем во временную папку
  });
}

This task is dependent on another (script) and generates the following file:
// .tmp/serve/app/config.js
angular.module('app.config')
  .constant('config', {
    "api": {
      "scheme": "http",
      "host": "localhost",
      "port": 8080,
      "root": "/api/v1/"
    }
  });

Next, I added this script to the list for injection into html. In index.js, I defined the module itself and added it as a project-wide dependency so that any child module would have access to these settings:
// src/app/index.js
angular.module('app.config', []);
angular.module('lemonfront', [
  'ngAnimate',
  'ngCookies',
  'ngSanitize',
  'ui.router',

  'app.config',
  'app.core'
]);

In Angular, it is now enough to inject config:
angular.module('...', [])
.factory(SomeService, ['config', function (config) {
  console.log(config.api.host);
}]);

And the choice of the config goes through the argument when starting gulp:
gulp build --env=prod

E
Evgeny Kumanin, 2015-07-08
@jackkum

There is such a thing yeoman.io/generators and the actual generator itself https://github.com/DaftMonk/generator-angular-fullstack
I really like the organized structure and use of the grunt command
. The dev project will start, with debugs and other goodies.
Start production
To add new modules, just use the commands:

bower install --save module-name
npm install --save module-name

At startup, these modules are injected into the index.html file, and in the production version, all files are minified.
Settings are stored like this:
./server/config/environment/development.js - dev version
./server/config/environment/production.js - prod version
./server/config/environment/index.js -
general
server side generator
client side
Deployment
Example:
$ yo angular-fullstack:endpoint post
[?] What will the url of your endpoint to be? /api/posts

S
Sergey, 2015-07-08
Protko @Fesor

make a config.dev.js file or something like that and write something like this there:

angular.module('app.config', [])
    .constant('API_ENDPOINT', 'http://api-dev.example.com')
;

and make our application dependent on it and use constants.
Then there are options:
1) when assembling, connect the necessary file
2) inline the file with configurations into the page.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question