• Stars
    star
    174
  • Rank 219,104 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🔧 Create AngularJS constants from a JSON config file

gulp-ng-config

License NPM version NPM version Build Status Coverage Status Code Climate Dependency Status

NPM

It's often useful to generate a file of constants, usually as environment variables, for your Angular apps. This Gulp plugin will allow you to provide an object of properties and will generate an Angular module of constants.

To Install:

npm install gulp-ng-config

How it works

It's pretty simple: gulpNgConfig(moduleName)

Example Usage

We start with our task. Our source file is a JSON file containing our configuration. We will pipe this through gulpNgConfig and out will come an angular module of constants.

var gulp = require('gulp');
var gulpNgConfig = require('gulp-ng-config');

gulp.task('test', function () {
  gulp.src('configFile.json')
  .pipe(gulpNgConfig('myApp.config'))
  .pipe(gulp.dest('.'))
});

Assume that configFile.json contains:

{
  "string": "my string",
  "integer": 12345,
  "object": {"one": 2, "three": ["four"]},
  "array": ["one", 2, {"three": "four"}, [5, "six"]]
}

Running gulp test will take configFile.json and produce configFile.js with the following content:

angular.module('myApp.config', [])
.constant('string', "my string")
.constant('integer', 12345)
.constant('object', {"one":2,"three":["four"]})
.constant('array', ["one",2,{"three":"four"},[5,"six"]]);

We now can include this configuration module in our main app and access the constants

angular.module('myApp', ['myApp.config']).run(function (string) {
  console.log("The string constant!", string) // outputs "my string"
});

Configuration

Currently there are a few configurable options to control the output of your configuration file:

options.environment

Type: String Optional

If your configuration contains multiple environments, you can supply the key you want the plugin to load from your configuration file.

Example config.json file with multiple environments:

{
  "local": {
    "EnvironmentConfig": {
      "api": "http://localhost/"
    }
  },
  "production": {
    "EnvironmentConfig": {
      "api": "https://api.production.com/"
    }
  }
}

Usage of the plugin:

gulpNgConfig('myApp.config', {
  environment: 'production'
})

Expected output:

angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});

Nested Environment

If the configuration is nested it can be accessed by the namespace, for example

{
  "version": "0.1.0",
  "env": {
    "local": {
      "EnvironmentConfig": {
        "api": "http://localhost/"
      }
    },
    "production": {
      "EnvironmentConfig": {
        "api": "https://api.production.com/"
      }
    }
  }
}

Usage of the plugin:

gulpNgConfig('myApp.config', {
  environment: 'env.production'
})

Expected output:

angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});

Multiple Environment keys

Multiple environment keys can be supplied in an array, for example for global and environmental constants

{
  "global": {
    "version": "0.1.0"
   },
  "env": {
    "local": {
      "EnvironmentConfig": {
        "api": "http://localhost/"
      }
    },
    "production": {
      "EnvironmentConfig": {
        "api": "https://api.production.com/"
      }
    }
  }
}

Usage of the plugin:

gulpNgConfig('myApp.config', {
  environment: ['env.production', 'global']
})

Expected output:

angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});
.constant('version', '0.1.0');

options.constants

Type: Object Optional

You can also override properties from your json file or add more by including them in the gulp tasks:

gulpNgConfig('myApp.config', {
  constants: {
    string: 'overridden',
    random: 'value'
  }
});

Generating configFile.js

angular.module('myApp.config', [])
.constant('string', "overridden")
.constant('integer', 12345)
.constant('object', {"one":2,"three":["four"]})
.constant('array', ["one",2,{"three":"four"},[5,"six"]])
.constant('random', "value");

options.type

Type: String Default value: 'constant' Optional

This allows configuring the type of service that is created -- a constant or a value. By default, a constant is created, but a value can be overridden. Possible types:

  • 'constant'
  • 'value'
gulpNgConfig('myApp.config', {
  type: 'value'
});

This will produce configFile.js with a value service.

angular.module('myApp.config', [])
.value('..', '..');

options.createModule

Type: Boolean Default value: true Optional

By default, a new module is created with the name supplied. You can access an existing module, rather than creating one, by setting createModule to false.

gulpNgConfig('myApp.config', {
  createModule: false
});

This will produce configFile.js with an existing angular module

angular.module('myApp.config')
.constant('..', '..');

options.wrap

Type: Boolean or String Default value: false Optional

Presets:

  • ES6
  • ES2015

Wrap the configuration module in an IIFE or your own wrapper.

gulpNgConfig('myApp.config', {
  wrap: true
})

Will produce an IIFE wrapper for your configuration module:

(function () {
  return angular.module('myApp.config') // [] has been removed
  .constant('..', '..');
})();

You can provide a custom wrapper. Provide any string you want, just make sure to include <%= module %> for where you want to embed the angular module.

gulpNgConfig('myApp.config', {
  wrap: 'define(["angular"], function () {\n return <%= module %> \n});'
});

The reuslting file will contain:

define(["angular"], function () {
 return angular.module('myApp.config', [])
.constant('..', '..');
});

options.parser

Type: String Default value: 'json' Optional

By default, json file is used to generate the module. You can provide yml file to generate the module. Just set parser to 'yml' or 'yaml'. If your file type is yml and you have not defined parser, your file will still be parsed and js be generated correctly. For example, you have a config.yml file,

string: my string
integer: 12345
object:
  one: 2
  three:
    - four
gulp.src("config.yml")
.pipe(gulpNgConfig('myApp.config', {
  parser: 'yml'
}));

Generating,

angular.module('myApp.config', [])
.constant('string', "my string")
.constant('integer', 12345)
.constant('object', {"one":2,"three":["four"]});

options.pretty

Type: Number|Boolean Default value: false Optional

This allows JSON.stringify to produce a pretty formatted output string.

gulp.src('config.json')
.pipe(gulpNgConfig('myApp.config', {
  pretty: true // or 2, 4, etc -- all representing the number of spaces to indent
}));

Will output a formatted JSON object in the constants, instead of inline.

angular.module("gulp-ng-config", [])
.constant("one", {
  "two": "three"
});

options.keys

Type: Array Optional

If you only want some of the keys from the object imported, you can supply the keys you want the plugin to load.

Example config.json file with unwanted keys:

{
  "version": "0.0.1",
  "wanted key": "wanted value",
  "unwanted key": "unwanted value"
}

Usage of the plugin:

gulpNgConfig("myApp.config", {
  keys: ["version", "wanted key"]
})

Expected output:

angular.module("myApp.config", [])
.constant("version", "0.0.1")
.constant("wanted key", "wanted value");

options.templateFilePath

Type: String Optional

This allows the developer to provide a custom output template.

Sample template: angularConfigTemplate.html

var foo = 'bar';

angular.module("<%= moduleName %>"<% if (createModule) { %>, []<% } %>)<% _.forEach(constants, function (constant) { %>
.<%= type %>("<%= constant.name %>", <%= constant.value %>)<% }); %>;

Configuration:

{
  "Foo": "bar"
}

Gulp task:

gulp.src('config.json')
.pipe(gulpNgConfig('myApp.config', {
  templateFilePath: path.normalize(path.join(__dirname, 'templateFilePath.html'))
}));

Sample output:

var foo = 'bar';

angular.module('myApp.config', [])
.constant('Foo', 'bar');

Additional Usages

Without a json/yaml file on disk

Use buffer-to-vinyl to create and stream a vinyl file into gulp-ng-config. Now config values can come from environment variables, command-line arguments or anywhere else.

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

gulp.task('make-config', function() {
  var json = JSON.stringify({
    // your config here
  });

  return b2v.stream(new Buffer(json), 'config.js')
    .pipe(gulpNgConfig('myApp.config'))
    .pipe(gulp.dest('build'));
});

ES6/ES2015

An ES6/ES2015 template can be generated by passing wrap: true as a configuration to the plugin

Contributing

Contributions, issues, suggestions, and all other remarks are welcomed. To run locally just fork & clone the project and run npm install. Before submitting a Pull Request, make sure that your changes pass gulp test, and if you are introducing or changing a feature, that you add/update any tests involved.

More Repositories

1

MagicMirror

🔮 ReactNative smart mirror project
JavaScript
242
star
2

render-if

⚛ Lightweight React control flow rendering
JavaScript
147
star
3

angular-translate-once

💱 Extension of angular-translate for one time bindings
JavaScript
53
star
4

ReactNative-Redux-Todo-List

React Native + Redux
JavaScript
45
star
5

react-native-todo-empty-state-transition

Dribbble inspired UI+UX
JavaScript
30
star
6

slackify

Upload files or stdin pipes to Slack from your CLI
JavaScript
28
star
7

titanium-chromecast

📡 A Titanium Appcelerator GoogleCast SDK (chromecast) module
Objective-C
27
star
8

jquery-stockquotes

A stock quote jQuery plugin
JavaScript
17
star
9

ReactNative-Redux-Calculator

Redux implementation of the UI/UX from https://github.com/benoitvallon/react-native-nw-react-calculator
JavaScript
16
star
10

titanium-okhttp

⚡ OkHttp networking module for Android on Titanium
Java
14
star
11

vine-clone

A clone of Vine with my personal data
JavaScript
13
star
12

angular-digits

🔢 AngularJS module for Twitter Fabric Digits
JavaScript
12
star
13

stocks-taskbar

JavaScript
9
star
14

blackbox

Xfinity rPi streamer
JavaScript
7
star
15

jekyll-portfolio

My Jekyll (soon to be React+Nextjs) website
HTML
7
star
16

rxjs-store

Redux influenced RxJS Store
JavaScript
6
star
17

jekyll-environment-variables

Access environment variables from within your Jekyll project's liquid templates
Ruby
6
star
18

angular-chromecast

AngularJS wrappers for GoogleCast chrome sdk
JavaScript
6
star
19

HearthstoneCardTracker

Hearthstone card tracker built with Node, Electron, and React
JavaScript
5
star
20

covfefe-react

Put meaning behind your sentences covfefe
JavaScript
5
star
21

react-predicate

A control-flow library for React
JavaScript
5
star
22

rx-react

Vanilla React and RxJS as a state manager
JavaScript
4
star
23

arduino-huelight-radar

Arduino motion sensor powered Hue Lights
JavaScript
3
star
24

Craigslist-Scraper

Search across all of Craigslist
PHP
3
star
25

ValheimMods

C#
2
star
26

react-native-devtools

JavaScript
2
star
27

rxjs-react-store

React bindings for RxJS Store
JavaScript
2
star
28

react-native-redux-wunderlist

JavaScript
2
star
29

react-validation

JavaScript
2
star
30

smart-home

JavaScript
2
star
31

react-angular

JavaScript
2
star
32

angular-permutation-switch

An enhanced ng-switch and ng-message directive
JavaScript
2
star
33

iPhone-Receipt-Drawer

My personal project to manage my receipts
JavaScript
1
star
34

bash-todo-list

Shell
1
star
35

chrome-github-notifier

Github Notification Chrome App
JavaScript
1
star
36

react-native-fifteen-puzzle

Fifteen puzzle experimented with React Native
Objective-C
1
star
37

ajwhite

1
star
38

raspberry-pi-grocer

Smart Trashcan - grocery list automation with a barcode scanner & rPi2
JavaScript
1
star
39

es-repl

JavaScript
1
star
40

ajwhite.github.io

TypeScript
1
star
41

HowManyPeopleAreSick

JavaScript
1
star
42

ComfyDiscord

Discord tools for Comfy Valheim
JavaScript
1
star
43

cx-prototype

JavaScript
1
star
44

Valheim-Storefront

C#
1
star
45

Insanequarium

Java
1
star
46

styled-system-spike

Created with CodeSandbox
JavaScript
1
star
47

fluid-labels

jQuery plugin for fluid labels
JavaScript
1
star
48

Apache-Configuration-Builder

A handy tool to streamline your new virtual host environments within Apache
Shell
1
star
49

Live-Lightning-Visualization

JavaScript
1
star
50

glamorous-native-slides

JavaScript
1
star
51

iCalUmass

Translate Umass calendars into iCalendar ics files
PHP
1
star
52

poke-level

JavaScript
1
star
53

botkit-react

JavaScript
1
star
54

EmojiWeather

JavaScript
1
star
55

Snake

The game of snake
JavaScript
1
star
56

rxjs-store-logger

JavaScript
1
star
57

ValheimWorldAnalyzer

C#
1
star
58

PokeScout

Alerts slack channels when specific Pokemon are nearby
JavaScript
1
star