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

rs-envconfig

v1.0.1

Published

Configuration utility for Angular app based on the environment variables

Downloads

8

Readme

ngx-envconfig

Configuration utility for Angular app based on the environment variables. Tweet

Using JSON files configure your Angular app like a BOSS!

Specify a list of API endpoints in the JSON and get them in your code with ease.

Look how beautiful is your code :blush:

Configuring your app for each environment be like:

Did you like it? Please put a Github star to support.

Table of contents:

  1. Features

  2. Installation

  3. Build Environments

  4. API Reference

    4.1 ConfigModule

    4.2 ConfigService

  5. Getting Started

    5.1 Setting up configuration files

    5.2 Usage without Angular environment variables

    5.3 Usage with Angular environment variables

Features

  • Configure the project for staging, development and production environments, by taking advantage of Angular environment variables.
  • Fallback to default (development.json) configuration if there is no match in production/staging configuration.
  • Initializ configuration, before whole application initialization process complete
  • Simplified methods for getting back-end API endpoints

Installation

npm install ngx-envconfig --save

Build Environments

  • ng build --configuration=staging builds for staging environment. For older versions ng build --env=staging
  • ng build --configuration=production builds for production environment. For older versions ng build --env=prod

Getting Started

Setting up configuration files

  • Create /config folder under /assets directory
  • Create the following config files for the appropriate environment under /assets/config folder.
// src/assets/config/development.json
{
  "HOST_API": "http://development.server.com",
  "API_ENDPOINTS": {
    "USER": "/api/v1/user"
  },
  "TOKEN": "development token"  
}
// src/assets/config/staging.json
{
  "HOST_API": "http://staging.server.com",
  "TOKEN": "staging token"
}
// src/assets/config/production.json
{
  "HOST_API": "http://production.server.com",
  "TOKEN": "production token"
}

Usage without Angular environment variables

// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { ConfigModule } from 'ngx-envconfig';

@NgModule({
    imports: [
        ConfigModule.forRoot({state: 'development'})
        ...
    ],
    providers: [
        ...
        Your Providers
        ...
    ]
})

export class AppModule { }
// src/app/app.component.ts
import { Component } from '@angular/core';

import { ConfigService } from 'ngx-envconfig';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private configService: ConfigService){
      console.log(configService.get('HOST_API'))
      // prints: http://development.server.com
      console.log(configService.getApi('USERS'))
      // prints: http://development.server.com/api/v1/users
      // prints: http://production.server.com/api/v1/users if the state is production
  }
}

Usage with Angular environment variables

  • Add staging configurations in angular.json file. Make sure production configuration is added. Default one we assume is the development configuration, which is points to environment.ts file.

    ...
    "projects": {
        "YOUR APP NAME": {
        "root": "",
        ...
            "architect": {
                "build": {
                ...
                "configurations": {
                    "production": {
                        "fileReplacements": [
                            {
                            "replace": "src/environments/environment.ts",
                            "with": "src/environments/environment.prod.ts"
                            }
                        ],
                        ...
                    },
                    "staging": {
                        "fileReplacements": [
                            {
                            "replace": "src/environments/environment.ts",
                            "with": "src/environments/environment.staging.ts"
                            }
                        ]
                    }
    ...
    }
  • If you have older version of Anuglar then make the updates in .angular-cli.json file as follows:

    "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts",
        "staging": "environments/environment.staging.ts"
      }
  • Create the following files under /environments folder.

    // ./environments/environment.prod.ts
    export const environment = {
        state: 'production'
    };
    // ./environments/environment.staging.ts
    export const environment = {
        state: 'staging'
    };
    // ./environments/environment.ts
    export const environment = {
        state: 'development'
    };
  • Then you can add environment value to ConfigModule like this:

        // src/app/app.module.ts
        import { NgModule } from '@angular/core';
        import { ConfigModule } from 'ngx-envconfig';
    
        import { environment } from '../src/environments/environment'; // <-- add this line
    
        @NgModule({
            imports: [
                ConfigModule.forRoot(environment) // <-- pass environment variable
                ...
            ],
            providers: [
                ...
                Your Providers
                ...
            ]
        })
    
        export class AppModule { }
    // src/app/app.component.ts
    import { Component } from '@angular/core';
    
    import { ConfigService } from 'ngx-envconfig';
    
    @Component({
    selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent {
        constructor(private configService: ConfigService){
            console.log(configService.get('HOST_API'))
            // prints: http://development.server.com
            // prints: http://production.server.com if the state is production
    
            console.log(configService.getApi('USERS'))
            // prints: http://development.server.com/api/v1/users
            // prints: http://production.server.com/api/v1/users if the state is production
        }
    }
    

API Reference

ConfigModule

  • .forRoot(envConfig: EnvConfig) Based on the provided envConfig.state value, it will load the approprate *.json config file. It assumes that configuration json files are located under ./src/assets/config folder. Angular will bootstrap the app, only after the configuration *.json file is loaded.

EnvConfig

  • .state: string Specifies the environment. For instane if it's equalt to 'development' then will load development.json file from ./src/assets/config folder
  • .fallbackDev: boolean = false Indicates whether to get the value from development.json configuration if there is no match in the specified environment. For instance if "SOME_KEY" does not exist in production.json then it will return the value of "SOME_KEY" from development.json, if "SOME_KEY" value does exist development.json file.

ConfigService

  • .get(propertyName: string): any. Returns the corresponding value of the provided property propertyName config file.
    constructor(private config: ConfigService){
      console.log(this.config.get('HOST_API'))
      // prints: 'http://development.server.com' in development mode  
    }
  • .getEnv(): string. Returns the current environment
    constructor(private config: ConfigService){
      console.log(this.config.getEnv())
      // prints: 'development' in development mode
    }
  • .isDevMode(): boolean. Returns true if environment is development, otherwhise false
    constructor(private config: ConfigService){
      console.log(this.config.isDevMode())
      // prints: true in development mode
    }
  • .getApi(endpoint: string): string. This function will only work if you have provided "API_ENDPOINTS" object in cofig file, which provides the list of available API endpoints and "HOST_API" which is the API's host URL. Returns API endpoint from "API_ENDPOINTS" by concatenating it with "HOST_API".
    constructor(private config: ConfigService){
      console.log(this.config.getApi('USER'))
      // prints: 'http://development.server.com/api/v1/user' in development mode  
    }
  • .onLoad: AsyncSubject boolean. Async subject to be subscribed. Emits when the config file is already loaded.
    constructor(private config: ConfigService){
      this.config.onLoad.subscribe(()=>{
          console.log('Config file is loaded');
      })
    }