npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

grunt-ng-constant

v2.0.3

Published

Plugin for dynamic generation of angular constant modules.

Downloads

28,078

Readme

grunt-ng-constant CircleCI

Plugin for dynamic generation of angular constant and value modules.

Getting Started

This plugin requires Grunt ~0.4.5

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-ng-constant --save-dev

When the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-ng-constant');

The "ngconstant" task

Overview

The following shows a simple configuration for generating a config module with one constant and one value that contain your package information and debug config.

grunt.initConfig({
  ngconstant: {
    options: {
      name: 'config',
      dest: 'config.js',
      constants: {
        package: grunt.file.readJSON('package.json')
      },
      values: {
        debug: true
      }
    },
    build: {
    }
  },
})

For the target build the resulting file config.js looks like this:

angular.module('config', [])

.constant('package', {
  "version": "0.0.1",
  ...
})

.value("debug", true)

;

Options

name

Type: String

Required

The name of the constant module used in your angular project.

dest

Type: String

Required

The path where the generated constant module should be saved.

deps

Type: Array or Boolean

Default value: []

Optional

An array that specifies the default dependencies a module should have. When your module should not have any modules, so you can append the constants to an already existing one, you can set deps to false.

constants

Type: Object, String, Function

Default value: {}

Optional

If it is an object it gets automatically merged in all target constants definitions. This option should be used when you need a global constants definition for all your targets.

values

Type: Object, String, Function

Default value: {}

Optional

If it is an object it gets automatically merged in all target values definitions. This option should be used when you need a global values definition for all your targets.

wrap

Type: String or Boolean

Default value: false

Optional

A boolean to activate or deactivate the automatic wrapping. A string which will wrap the result of file, use the {%= __ngModule %} variable to indicate where to put the generated module content. See the "Custom Wrap Option" section for further informations.

serializer

Type: String|Function

Default value: jju

Optional

Available options:

  • jju (Default) Uses the jju stringify method.
  • json Uses JSON.stringify for serialization.
  • tosource Use the node-tosource module.

If you want to define your own serializer use function(obj, serializerOptions, options) { return /* your serialized string */ }. this will be set to the plugin context.

serializerOptions

Type: Object

Default value: {indent: '', no_trailing_comma: true}

Optional

Use this option for setting specific options for the given serializer. The default config configures the jju stringify method. See the documentation for more information of possible options.

template

Type: String

Default value: grunt.file.read('constant.tpl.ejs')

Optional

Custom template for creating the output constants file. Defaults to the default constants template file if none provided.

delimiters

Type: String

Default value: 'ngconstant' which sets the template delimiters to {% and %}. Make sure that you do not use the same delimiters as your grunt configuration or you get an unwanted behavior.

Optional

configMergeCustomizer

Type: Function

Default value: _.noop

Optional

Allows to customize the merge of global and target configuration. The function has the signature (key, objValue, srcValue, key, object, source, stack). The key parameter can be 'constants' or 'values'. The rest of the parameters is identical to _.mergeWith.

Usage Examples

Default Options

In this example I convert the package.json information to an angular module. So I am able to display such things as the current version of the application in the app.

grunt.initConfig({
  ngconstant: {
    dist: {
      options: {
        dest: 'dist/constants.js',
        name: 'constants',
      },
      constants: {
        package: grunt.file.readJSON('package.json')
      },
      values: {
        debug: true
      }
    }
  },
})

Note: In most cases for all following examples the applied functionality on constants can also be achieved with the values parameter.

Custom Options

In this example we set custom configurations for the space and deps parameters. So we create a module that has dep1 and dep2 as dependencies and defines two different constants constants1 and constants2 with custom values. The space parameter is set to a .

grunt.initConfig({
  ngconstant: {
    options: {
      space: ' ',
      deps: ['dep1', 'dep2'],
      dest: 'dist/module.js',
      name: 'someModule'
    },
    dist: {
      constants: {
        'constant1': {
          'key1': 'value1',
          'key2': 42
        },
        'constant2': 'value2'
      }
    }
  },
})

The resulting module looks like the following:

angular.module("someModule", ["dep1", "dep2"])

.constant("constant1", {
  "key1": "value1",
  "key2": 42
})

.constant("constant2", "value2")

;

You can also load the constants definition directly from a file:

grunt.initConfig({
  ngconstant: {
    options: {
      dest: 'dist/module.js',
      name: 'someModule'
    },
    dist: {
      constants: 'constants.json'
    }
  },
})

Or if you want to calculate the constants value at runtime you can create a lazy evaluated method which should be used if you generate your json file during the build process.

grunt.initConfig({
  ngconstant: {
    options: {
      dest: 'dist/module.js',
      name: 'someModule'
    },
    dist: {
      constants: function () {
        return {
          lazyConfig: grunt.file.readJSON('build/lazy-config.json')
        };
      }
    }
  },
})

Wrap Option

The wrap option allows you to encapsulate the module in a closure. Simply set wrap to true.

grunt.initConfig({
  ngconstant: {
    options: {
      dest: 'tmp/wrap_options.js',
      name: 'module2',
      wrap: true
    },
    dist: {
      constants: {
        'constant1': {
          key1: 123,
          key2: 'value2',
          foobar: false
        }
      }
      
    },
    nowrap: { 
      options: {
        wrap: false // Disable wrapping for the 'nowrap' target
      },
      constants: {
        ...
      }
    }
  },
})

The resulting module looks like:

(function(angular, undefined) {
   angular.module("module2", ["test"])

.constant("constant1", {
  "key1": 123,
  "key2": "value2",
  "foobar": false
})

; 
})(angular);

Custom Wrap Option

If you want to use another wrapping you can use a string as wrap option, which is interpolated by the plugin. Use the __ngModule variable as placeholder for the generated module.

Here a RequireJS example:

grunt.initConfig({
  ngconstant: {
    options: {
      dest: 'tmp/wrap_options.js',
      name: 'module2',
      wrap: 'define(["angular", "ngResource", "ngCookies"], function() { \n return {%= __ngModule %} \n\n});',
    },
    dist: {
      constants: {
        'constant1': {
          key1: 123,
          key2: 'value2',
          foobar: false
        }
      }
    }
  },
})

The resulting module looks like the following:

define(["angular", "ngResource", "ngCookies"], function() { 
 return angular.module("module2", ["test"])

.constant("constant1", {
  "key1": 123,
  "key2": "value2",
  "foobar": false
})

; 

});

Note: For longer wrapping templates it is recommended to use grunt.file.read('customer-wrap.tpl.ejs').

Global Constants option

If you need the same configuration for all your targets you can use the constants option to automatically merge your per target configuration into the global one. If you don't want to merge, you can use the per target constants option to override everything.

grunt.initConfig({
  ngconstant: {
    options: {
      name: 'config',
      dest: 'config.js',
      constants: {
        title: 'grunt-ng-constant',
        debug: true
      }
    },
    dev: {
      constants: {
        title: 'grunt-ng-constant-beta'
      }
    },
    prod: {
      constants: {
        debug: false
      }
    },
    override_global: {
      options: {
        constants: { // This does not merge it overrides
          ...
        }
      }
    }
  }
});

Which results in the following constants objects.

For the target dev:

angular.module('config', [])

.constant('title', 'grunt-ng-constant-beta')

.constant('debug', true)

;

For the target prod:

angular.module('config', [])

.constant('title', 'grunt-ng-constant')

.constant('debug', false)

;

FAQ

How can I change the style of the generated code?

If the code looks to ugly for you. You can use grunt-jsbeautifyer.

How can I create multiple modules?

Create a custom target for each module and set the dest, name, constants and values parameter for each one.

How can I create a CoffeeScript version of the module

Till v1.0.0 this was supported natively by the plugin. Now you have to use the grunt-js2coffee plugin.

Hey I like this project how can I help?

Report bugs, propose new features or simply star the project that shows me that are people are interested in this project.

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.