GithubHelp home page GithubHelp logo

guzart / gulp-ng-constant Goto Github PK

View Code? Open in Web Editor NEW
109.0 3.0 26.0 62 KB

Gulp plugin for dynamic generation of angular constant modules.

License: MIT License

JavaScript 92.49% HTML 7.51%
gulpfile gulp-plugins angular1

gulp-ng-constant's Introduction

gulp-ng-constant

License NPM version NPM version
Build Status Code Climate Dependency Status

Information

Packagegulp-ng-constant
Description Plugin for dynamic generation of angular constant modules.
Based of grunt-ng-constant
Node Version >= 0.10

Index

  1. Usage
  1. Options
  1. Examples
  1. Special Thanks

Usage

Configuration in gulpfile.js

gulpfile.js

var ngConstant = require('gulp-ng-constant');

gulp.task('config', function () {
  gulp.src('app/config.json')
    .pipe(ngConstant({
      name: 'my.module.config',
      deps: ['ngAnimate'],
      constants: { myPropCnt: 'hola!' },
      wrap: 'amd',
    }))
    // Writes config.js to dist/ folder
    .pipe(gulp.dest('dist'));
});

app/config.json

{
  "myFirstCnt": true,
  "mySecondCnt": { "hello": "world" }
}

dist/config.js (output)

define(["require", "exports"], function(require, exports) {
  return angular.module("my.module.config", ["ngAnimate"])
    .constant("myFirstCnt", true)
    .constant("mySecondCnt", { "hello": "world" })
    .constant("myPropCnt", "hola!");
});

Configuration in config.json

gulpfile.js

var ngConstant = require('gulp-ng-constant');

gulp.task('config', function () {
  gulp.src('app/config.json')
    .pipe(ngConstant())
    // Writes config.js to dist/ folder
    .pipe(gulp.dest('dist'));
});

app/config.json

{
  "name": "my.module.config",
  "deps": ["ngAnimate"],
  "wrap": "commonjs",
  "constants": {
    "myFirstCnt": true,
    "mySecondCnt": { "hello": "world" }
  }
}

dist/config.js (output)

module.exports = angular.module("my.module.config", ["ngAnimate"])
    .constant("myFirstCnt", true)
    .constant("mySecondCnt", { "hello": "world" })
    .constant("myPropCnt", "hola!");

Options

options.name

Type: string
Default: filename or "ngConstants"
Overrides: json.name
optional

The module name. This property will override any name property defined in the input json file. The default name when used as a transform stream (i.e. regular plugin) is the passed file name. When options.stream is true the default name is "ngConstants".

options.stream

Type: boolean
Default: false
optional

If true it returns a new gulp stream, which can then be piped other gulp plugins (Example).

options.constants

Type: Object | string
Default: undefined
Extends/Overrides: json.constants

Constants to defined in the module. Can be a JSON string or an Object. This property extends the one defined in the input json file. If there are properties with the same name, this properties will override the ones from the input json file.

options.merge

Type: boolean
Default: false
optional

This applies to constants of the Object type. If true the constants of type Object from the input file and the constants from the configuration will be merged.

options.deps

Type: array<string>|boolean
Default: []
Overrides: json.deps
optional

An array that specifies the default dependencies a module should have. To add the constants to an existing module, you can set it to false. This property will override any deps property defined in the input json file.

options.wrap

Type: boolean|string
Default: 'es6'
Available: [false, 'amd', 'commonjs', 'es6']
optional

A boolean to active or deactive the automatic wrapping. A string who will wrap the result of file, use the <%= __ngModule %> variable to indicate where to put the generated module content. A string with 'amd' that wraps the module as an AMD module, compatible with RequireJS

options.wrapHeader

Type: string
Default: null
optional

A string that is prepended to the wrapper.

options.wrapFooter

Type: string
Default: null
optional

A string that is appended to the wrapper.

options.space

Type: string
Default: null
optional

A string that defines how the JSON.stringify method will prettify your code, e.g. '\t', ' '

options.template

Type: string
Default: content of tpls/constant.tpl.ejs
optional

EJS template to apply when creating the output configuration file. The following variables are passed to the template during render:

  • moduleName: the module name (string)
  • deps: the module dependencies (array<string>)
  • constants: the module constants (array<contantObj>)
    • where a constantObj is an object with a name and a value, both strings.

options.templatePath

Type: string
Default: 'tpls/constant.tpl.ejs'
optional

Location of a custom template file for creating the output configuration file. Defaults to the provided constants template file if none provided.

options.indent

Type: string
Default: '' (empty string)
optional

A string that is used to indent the .constant() lines in the generated file. Useful only for formatting the output file.

Examples

Multiple Environments

config.json

{
  "development": { "greeting": "Sup!" },
  "production": { "greeting": "Hello" }
}

gulpfile.js

var gulp = require('gulp');
var ngConstant = require('gulp-ng-constant');

gulp.task('constants', function () {
  var myConfig = require('./config.json');
  var envConfig = myConfig[process.env];
  return ngConstant({
      constants: envConfig,
      stream: true
    })
    .pipe(gulp.dest('dist'));
});

Stream

var gulp = require('gulp');
var ngConstant = require('gulp-ng-constant');
var uglify = require('gulp-uglify');

gulp.task('constants', function () {
  var constants = { hello: 'world' };
  return ngConstant({
      constants: constants,
      stream: true
    })
    .pipe(uglify())  
    .pipe(gulp.dest('dist'));
});

YAML

Just write your configuration in a YAML file and pipe it to the plugin.

config.yml

greeting: Merry Christmas!
seasons:
  - Winter
  - Spring
  - Summer
  - Fall

gulpfile.js

var gulp = require('gulp');
var ngConstant = require('gulp-ng-constant');

gulp.task('constants', function () {
  gulp.src('app/config.yml')
    .pipe(ngConstant())
    .pipe(gulp.dest('dist'));
});

ECMAScript 2015 (ES6)

envs.json

{
  "development": {
    "ENV": {
        "KEY": "secret",
        "API_URL": "http://localhost/"
    }
  },
  "production": {
    "ENV": {
        "KEY": "superSecret",
        "API_URL": "http://example.com/"
    }
  }
}

gulpfile.babel.js

import gulp     from 'gulp';
import rename   from 'gulp-rename';
import ngConstant from 'gulp-ng-constant';

gulp.task('constants', function () {
  var myConfig = require('./envs.json');
  var envConfig = myConfig[process.env];
  return ngConstant({
      name: "app.env",
      constants: envConfig,
      stream: true,
      wrap: "es6"
    })
    .pipe(rename('env.js'))
    .pipe(gulp.dest('dist'));
});

app.js

'use strict';

import angular from 'angular';
import env from 'env';

let app = angular.module('app', [env.name])
    .factory('someRepository', function($http, ENV) {
        //Just to illustrate
        $http.get(ENV.API_URL);
    });


export default app;

Special Thanks

@alexeygolev, @sabudaye, @ojacquemart, @lukehorvat, @rimian, @andidev, @dotDeeka, @LoicMahieu, @vladimirgamalian

gulp-ng-constant's People

Contributors

alexeygolev avatar andidev avatar guzart avatar jwoos avatar loicmahieu avatar lukehorvat avatar ojacquemart avatar thedancingcode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

gulp-ng-constant's Issues

Add consumption example to documentation

This is an awesome and very, very, very useful bit of code that I'm glad to have.

Unfortunately, while the data is definitely getting exported to an AngularJS file, I have no clue how to actually consume it. I imagine someone who has already done a lot of work with Angular could get there quickly -- I am not that person. Not yet. A little bit more documentation would be... very helpful.

New release with es6?

Hi
I've just looked at your fine package, and would like a new release where you es6-templates are included via npm. The newest release (1.1.0) does not include the es6 template/wrapper.

Do you have any plans for the next release? I would love to help if I can.

file name as constant name

I have clean config.json without constant names. Only parameters. I don't want to see constant name in my config. Add parameter "constantName" or "nameFromFile" to ng-constant

ES6 being used without wrap: es6

I am not using wrap: es6 but yet I am getting es6 syntax which breaks on my build:

var ngConstantOpt = {
    space: '  ',
    name: 'app',
    stream: true,
    constants: {
        API_BASE_URI: '/'
    }
}


function callNgConstant(constant) {
    ngConstantOpt.constants.API_BASE_URI = constant;
    return ngConstant(ngConstantOpt)
        .pipe(rename("base-uris.js"))
        .pipe(gulp.dest(baseFileAbsPath));
};

gulp.task('constants:dev', function () {
    return callNgConstant('/')
});

import angular from 'angular';

const env = angular.module("app", [])
.constant("API_BASE_URI", "/");


export default env;

Replace deprecated dependency gulp-util

Replace deprecated dependency gulp-util

gulp-util has been deprecated recently. Continuing to use this dependency may prevent the use of your library with the latest release of Gulp 4 so it is important to replace gulp-util.

The README.md lists alternatives for all the components so a simple replacement should be enough.

Your package is one of the most popular packages still relying on gulp-util, it would be good to publish a fixed version to npm as soon as possible.

See:

configuration question

Hi there,
great plugin!

Qq what is the right way to set up devel & production config.js.
I ended up having two gulp tasks and two config.json files.
How would you do it? When I look at grunt-ng-constant there seams to be a different way to do this.

Thank you!

Error after upgrading to 2.0.0-1

The following error only happens in the new version:

[10:25:46] Starting 'config'...
[10:25:46] 'config' errored after 17 ms
[10:25:46] ReferenceError in plugin 'gulp-tslint-log'
Message:
    wrapHeader is not defined
Details:
    fileName: ngConstants.json

The previous version (1.1.0) works fine!

My Gulp task:

gulp.task('config', () => {
  const myConfig = require(`./${appConfig.app}/scripts/config/config.json`);
  const envConfig = myConfig[environment];
  return ngConstant({
      constants: envConfig,
      name: 'MyAngularApp',
      deps: false,
      stream: true
    })
    .pipe(rename('app-config.js'))
    .pipe(gulp.dest(`${appConfig.app}/scripts/config`));
});

Please upload newest build to npm - Parsing .yml files

Hi,

I'm trying to parse config saved in .yml file. But unfortunately, I'm still getting errors like
'SyntaxError: Unexpected token a'

Here's the code causing this:
var data = file.isNull() ? {} : JSON.parse(file.contents); (index.js, line 47)

After a quick research, I found out that the following commit should fix it:
adca6bd

So it turns out there's obsolete version on the npm. Could you please upload newest build?

deps: false works incorrect

If I write deps: false I get module('name') without dependencies [] (as in grunt-ng-constant). It usefull if I want to use existent module

create multiple constants under same ngModule

I have two json file en.json and np.json and I would like to create constants under same module name app.constants
gulp.task('translations', function() { gulp.src(['en.json', 'np.json']) .pipe(ngConstants({ name: 'app.constants', wrap:false, })) .pipe(concat('constants.js')) .pipe(uglify()) .pipe(gulp.dest('./dist')); });
but what I get is module is defined multiple times

angular.module("app.constants", []).constant("i18en", { NAME: "Shankar" }), angular.module("app.constants", []).constant("i18np", { NAME: "शंकर" });

Lint warnings/errors on generated constant module

While dependency injecting a generated constant module, I get the following lint errors/warnings

  line 2  col 3   Missing "use strict" statement.
  line 2  col 37  Strings must use singlequote.

I'm aware that I can create own template files to avoid these lint entries but I think it would be a good idea if this could work directly.

Adding an object constant

Hi can you advise if it is possible to add object constants and the best practice for adding these .
This technique tends to be used for injecting third party objects that are assigned to the global.

e.g.

.constants("moment",moment)

If I try this in gulp I get a reference error moment is undefined.
I can add this manually and have no issues and works as expected but would like to add as part of the build process if possible.
Thanks

Overriding Values?

Hi:

I would like to have a base set of config values, and then override only certain values in an environment-specific config. I'm having hard time figuring out how to get gulp-ng-constant to do that. Can you give me a hint.

Example:
app.config.json would look like this:
{
"foo": "default",
"bar": "default"
}
app.dev.json might look like this:
{
"foo":"dev"
}

I want output to look like this
.constant("foo", "dev")
.constant("bar": "default")

I can't seem to make that work. (either app.dev.json completely overwrites app.config.json, so "bar" gets dropped, or app.config.json completely overwrites app.dev.json)

Add ability to disable jscs on constant file

It would be great if there was an ability to add the disable jscs check comment on the constant generated file as I follow the airbnb javascript convention of using single quotes for strings rather than double quotes (which is the standard for json).

Use better defaults that match modern style

  • Better es6 template #34
  • Use a different JSON.stringify that outputs the constants values (single quotes) #24 #26
  • Add strict template for angular 1? #36
  • Add path option to extract the values from a given path
  • Add environment variable that internally uses path

Group under one single constant name.

Hi,

I didn't find the possibility to group under one single constant name.

Example

Given an object like:

{
"person": "samir",
"age": 99
}
I wanted to get this:

angular.module("conf", [])
.constant("CONFIG", {
"person": "samir",
"age": 99
});
but instead got this:

angular.module("conf", [])
.constant("person", "samir")
.constant"age", 99);
Using an optional parameter we can simply group the whole object under a user defined constant.

Let me know if you think this feature makes sense and I'll write the tests and update README to include an example (I just added the option explanation for now).

Gulp signals task did not complete

Here's my code. I have many other tasks that use this same syntax, and they're working great.
For some reason I'm getting this message after I run my task:

[11:24:53] The following tasks did not complete: build, buildEnvironmentConstants
[11:24:53] Did you forget to signal async completion?

I'm trying to simplify this down to it's most basic usage so I can eliminate other problems. What's wrong here?

module.exports = (gulp, plugins, config) => {
    return function buildEnvironmentConstants(done) {
        return plugins.ngConstant({
            name: 'testname',
            constants: {},
            stream: true
        })
        .pipe(gulp.dest(config.JS_APP_BUILD_OUPUT_DIR))
    };
};

Removing module dependencies via configuration

I want to remove dependency injection array passed in to module completely....right now I get a blank dependency array. Is there some value I can pass like in grunt deps: false to completely remove angular.module('modulename', [ ]) to be angular.module('modulename')?

JSON as single constant

Just FYI for future users, my use case was converting a JSON dictionary into a single app constant. My flow was using a gulp module to create a json file which then is converted into Angular constant.

Thanks for providing the EJS template ability to customize the output.

angular.module("<%- moduleName %>"<% if (deps) { %>,${JSON.stringify(deps)}<% } %>)
${indent}.constant({"myDictionary": {

<% constants.forEach(function(constant) { %>
"<%- constant.name %>": ${constant.value},
<%= _.last(constants) === constant ? '' : '\n' %>

<% }) %>}});

Constants replaced instead of merged

I have a gulp-ng-constant task like this:

gulp.task('config', function() {
  var configPath = 'env.json';

  return gulp.src(configPath)
    .pipe($.ngConstant({
      name: 'app.env',
      constants: { env: { authPath: /profiles/authenticate/ } },
      wrap: 'commonjs'
    }))
    .pipe(gulp.dest(path.join(conf.paths.src, '/app')));
});

and an env.json file like this:

{
  "env": {
    "backend": "http://0.0.0.0:8000",
  }
}

Given those parameters, I end up with an env.js file like this:

module.exports = angular.module("app.env", [])

.constant("env", {
    "authPath": "/profiles/authenticate/"
})

;

I expected the constants in the json file to be merged rather than replaced since an extra variable isn't likely to cause problems vs. a missing variable. Agree, disagree?

use template instead of templatepath

It would be nice if your module would use a template directly instead of the templatePath.
This would allow to define the template directly in the gulp file without the need of a template file.
Using a template in a file would still be possible as this is the same as template: JSON.parse(fs.readFileSync(templatePath))

Using a template would allow more flexibility in defining the constants.

What do you think?

Setting a custom filename for the outputted file via options?

Hi there,

I am currently using the gulp-ng-constant module as follows:

ngConstants = require('gulp-ng-constant');

gulp.task('create-version-file', [], function () {
    var constants = { version: '1.0.0' };
    return ngConstant({
        constants: constants,
        wrap: false,
        deps: [],
        stream: true,
        name: 'myapp.version'
      })
        .pipe(gulp.dest('dist'))
});

However, doing so, creates an Angular constants file named ngConstants.js. Forcing a filename in gulp.dest by specifying a full path, as in gulp.dest('dist/version.js') creates a directory called version.js (which contains the generated ngConstants.js file) inside the dist directory.

No option seems to exist to specify the filename of the generated constants file. Is it so, or am I missing something in the docs?

Thanks in advance!

Version 2 released as version 1.2

I don't know if this is intentional or not but it broke a build process that was looking for ngConstants.js and then couldn't find it due to the new way output filenames are done.

merge constants from files in the stream

from @intellix comment on #6

I'm trying to have 2 configs merged so I can have global configuration and environment specific ones like:

config-global.json {
    ENV: {
        name: 'MyApp'
    }
}
config-dev.json {
    ENV: {
        apiEndpoint: 'localhost'     
    }
}

to create:

config.js {
    ENV: {
        name: 'MyApp'
        apiEndpoint: 'localhost'
    }
}

so that the following will get the constants from config/global.json and extend or override them with config/dev.json:

gulp
  .src([ 'config/global.json', 'config/dev.json' ])
  .pipe($.ngConstant({
    name: 'config'
  }))
  .pipe(gulp.dest('src/app'));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.