Archive for June, 2017

June 7th, 2017
10:45 am
Using lite-server to run an angular application

Posted under Angular
Tags ,

lite-server is useful when it is desired to serve an application using actual files, in contrast with ng serve which serves everything from memory. A comparison follows:-

ng serve

This uses webpack to build and serve the application entirely from memory. The consequence of this is that any files (such as external configuration files) which are not specifically part of the angular-cli/webpack bundles/built by webpack will not be available/visible when the application is served. Additional script files can be included in the build bundles by adding to the scripts property in .angular-cli.json, but of course if this is done they are not then external to the build.

lite-server used in development mode

Having installed lite-server globally, it can be used in the following way such that file changes are monitored and updated dynamically in the build :-

under linux:-

ng build –watch && cd dist && lite-server

under windows:-

ng build –watch
rem then under a separate command session:-
cd dist
lite-server

 

lite-server used in production mode

This will do a production build with AOT enabled by default:-

ng build –prod
cd dist
lite-server

No Comments »

June 6th, 2017
5:58 pm
Angular/Ionic–externalising application configuration

Posted under Angular & Ionic & TypeScript
Tags , , , ,

Key Goals

  1. The primary goal is to completely decouple configuration data from the build deployment. This is a key requirement in an enterprise setting, not least because it is vital that the very same build can be tested and signed off in a number of different development and test environments pointing at different server infrastructure.  If a different build was needed for each environment, there is always the risk of an incorrect build, so technically the final production build has never been tested and could break. A good discussion on this may be found on The Twelve Factor App site here.
  2. Upon investigating a pattern for this in Ionic and Angular, I found numerous posts citing different ways around the problem, some appearing quite complex. I was left feeling that this need was not something that had been baked in to the Framework design as a first class citizen – it was certainly not an up front and clear pattern in the documentation. Therefore I wanted a reusable pattern to use as a standard for all my Angular development.
  3. I am using angular-cli with webpack, which is the recommended approach. This produces simple static deployment bundles which are web server agnostic – just an html file which loads one or more js bundles, plus assets such as fonts and images. The pattern for externalising configuration aims to fit in with this and makes no assumptions about the ability to build configuration data dynamically server-side or inject configuration related information into the web server. For example, a common pattern when using Apache Tomcat with Java applications is to inject a configuration location as a JVM parameter into tomcat, which is used later server-side to access the configuration dynamically. We make no assumptions here about the ability to do this kind of trick – any such mechanisms (discussed further below) would be an extension to the pattern for a particular server.
  4. An important goal of the pattern is that it should be testable, i.e. we use dependency injection to inject configuration into the classes that use it, (in our case via a service). This allows unit tests to inject test configuration as required.
  5. The pattern also supports offline use e.g. in an Ionic application. If, as some solutions advocate, the configuration was loaded via an HTTP service in javascript code, this would not work offline with Ionic. The challenge that remains is how and where the configuration would be located in an Ionic deployment, but that is a question for another day and further invesigation.

 

Solution Overview

  1. After a fair amount of investigation I settled on a fairly simple pattern as per this post here. This stackoverflow comment refers to the same technique.  I adapted the technique for my situation – the key points are as follows, and a code sample is shown below.
  2. The basic idea is to load configuration data as a Json object literal from a .js file. This is done by a <script> tag in index.html, prior to the loading of the webpack bundles, which loads the configuration typically as a file from a known location, where the src of the <script> tag is deemed not part of the build.
  3. Whilst this would typically be a location on the same server such as the root directory where index.html is located, it does not have to be, and could equally well be loaded from another server over http. The key point is that the precise src for the script tag is a contract between index.html and any deployment/configuration management software. For example, the configuration file might be dynamically created by Ansible or similar, or the configuration might not be a file at all, and could be dynamically created server side via a web service. These possibilities are all extensions to the basic pattern and depend on the particular web servers and deployment techniques in play.
  4. When running in development mode using ng serve, the bundles are created in memory and no files exist. Therefore this mechanism will not work as the <script> tag will not load anything. We therefore provide a means of having default configuration in the code which will be overridden by the above configuration file if present. If the configuration file is not present (ng serve in dev mode) you will get a 404 for the script tag on the console, which can be ignored.
  5. When running in development mode using files (e.g. via lite-server using  ng build –watch and running lite-server from the dist subdirectory), a config file can be used in the normal way to override the default config if desired.
  6. The default configuration object is exported as a constant from the appropriate environment file, e.g. environment.ts. Whilst there could be default settings in environment.prod.ts, the default is typically set to null in this case so that a configuration file is always used.
  7. The structure of the configuration data is typed via an AppConfig interface which is used everywhere the data is loaded or referenced. In simple cases the configuration data may be just properties of the root AppConfig object. However in more complex cases the object graph could be extensive.
  8. The configuration file loads the configuration object into a global variable which is then read by the AppConfigService, and if present overrides the default configuration. Object.freeze() is used (along with readonly properties on the AppConfig interface) to make the configuration data immutable. Whilst in theory it may be possible to inject the resulting configuration as a constant using a value provider, when I tried this (with the latest Angular 4) I hit a variety of intermittent compile/build errors citing ERROR in Error encountered resolving symbol values statically. In the end I went with an injected configuration service, which consuming classes set up as a getter to allow convenient access.
  9. The AppConfigService loads the global configuration variable via a casted reference to the window object. I tried to get this to work via a declare to reference it as an external object but again I hit compile errors when doing so.

 

Example Code Listings

 

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Places Admin</title>

<base href=”/”>

<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”icon” type=”image/x-icon” href=”favicon.ico”>

<script type=”text/javascript” src=”appConfig.js”></script>

</head>
<body>
<app-root>Loading…</app-root>
</body>
</html>

appConfig.js – external configuration file.

// Application Configuration
var salientSoft_appConfig = {
  appTitle: "The Places Guide",
  apiBase: "http://localhost:5984/places-guide/",
  messageTimeout: number = 3000
};

environment.ts

// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.

import {AppConfig} from ‘../config/app-config’;

export const environment = {
production: false,
};

export const defaultAppConfig: AppConfig = {
appTitle: ‘The Places Guide’,
apiBase: ‘http://localhost:5984/places-guide/’,
messageTimeout: 3000
};

environment.prod.ts

import {AppConfig} from '../config/app-config';

export const environment = {
production: true
};

export const defaultAppConfig: AppConfig = null;

appConfig.ts – config file interface

/* Root application configuration object
   This encapsulates the global config json properties.
   These must match what is in the actual config file, normally /appConfig.js.
 */
export interface AppConfig {
    readonly appTitle: string;
    readonly apiBase: string;
    readonly messageTimeout: number;
}

app-config.service.ts

import {Injectable} from '@angular/core';
import {AppConfig} from './app-config';
import {defaultAppConfig} from '../environments/environment';

@Injectable()
export class AppConfigService {
private _appConfig: AppConfig;
buildConfig(): AppConfig {
const appConfig: AppConfig = (<any>window).salientSoft_appConfig || defaultAppConfig;
return Object.freeze(appConfig);
}
constructor() {
this._appConfig = this.buildConfig();
}
get(): AppConfig {
return this._appConfig;
}
}

app.component.ts – example configuration consumer

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

constructor(
private appConfigService: AppConfigService
) {}

public get appConfig(): AppConfig {return this.appConfigService.get(); }

ngOnInit(): void {
document.title = this.appConfig.appTitle;
}

No Comments »