breaking down, package.json

01 | Using Config within package.json

package.json
{
  "name": "npm-labs",
  "version": "1.0.0",
  "description": "",
  "main": "start.js",
  "config": {
    "env": "dev"
  },
  "scripts": {
    "show-conf": "echo env: $npm_package_config_env",
    "first-task": "npm run second-task",
    "second-task": "npm run build --env=$npm_package_config_env",
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "node start.js"
  },
  "author": "hamzeen",
  "license": "ISC"
}
start.js
console.log("name:" + process.env.npm_config_env);

usage:

$ npm run first-task

02 | Passing args to JS file

package.json
{
  "name": "npm-labs",
  "version": "1.0.0",
  "description": "",
  "main": "start.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "node start.js"
  },
  "author": "hamzeen",
  "license": "ISC"
}
start.js
console.log("name:" + process.env.npm_config_name);

usage:

$ npm run build --name=app-name
Advertisements

Angular5 part-2

There is only word which is synonymous with Angular, C H A N G E. Few months ago I made a post on Angular2 & now we have landed on Angular5. It is definitely challenging to keep us on par with the latest in the Angular world.

So to keep my dice rolling, I decided to make my angular posts into a series. In this we look at debugging our unit tests on a browser. In Javascript world, we all know and/or have used Jasmine for Unit Testing at some point.

By default it runs on a headless browser (usually PhantomJS) so we launch the test case/suite from terminal & just wait till test results but we never get to see anything!

But if we change this to a browser like Chrome, we could actually see how the test cases are being executed. Just like UI automation tests, fro example, this would show us text being inserted on forms, button being clicked & etc. Without no more explaination, let’s dive into how we establish this; Just 3 steps!

01 | Get the karma chrome launcher for your project

npm install karma-chrome-launcher --save-dev

02 | Modify karma.conf.json to add the following

    customLaunchers: {
      Chrome_without_security: {
        base: 'Chrome',
        flags: ['--disable-web-security']
      }
    },
    broswers [
        'phantomJS','Chrome', 'Chrome_without_security'
    ]

03 | add the following script definition to package.json

"test-watch": "node node_modules/karma/bin/karma start --browsers=Chrome,Chrome_without_security --single-run=true --auto-watch",

That is it!

Now open up terminal from your project path and hit the following and see magic happen on chrome (look for port on the output)

npm run test-watch

Deploying Node.js app to Heroku


# login to Heroku if not SSH issues!
heroku login

# clone git repo to local drive
git clone git://abc.git

# install packages & build it
cd abc
npm install

# if gitignore found
remove contents of .gitignore

# important creates remote heroku branch & generates a dynamic name for the repo
heroku create
git push heroku master



#after changes
git add .
git commit -m “add local changes”
git push heroic master
heroku open or  heroku open cool

Angular5 part-1

01 | Template on Plunker

https://plnkr.co/edit/gQjnRg?p=info

02 | Setup a project locally using ng-cli

if you already have an older version:

npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli@latest

03 | Configure Routes

WARNING! AppComponent Shouldn’t be part of routing. But it is set as the default route by ng-cli.

> Never Use this:

{ path: '', component: AppComponent },

> Should use something like below:

import { Routes } from '@angular/router';
import { AppComponent } from './';
import { ContactComponent } from './contact/contact.component';
import { AboutComponent } from './about/about.component';

export const routes: Routes = [
  { path: '', redirectTo: '/contact', pathMatch: 'full' },
  { path: 'contact',  component: ContactComponent },
  { path: 'about',  component: AboutComponent },
  { path: '**', redirectTo: '/contact', pathMatch: 'full' },
];
Route Redirection: 
  { path: '**', redirectTo: '/contact', pathMatch: 'full' },
Wildcard Routes: 
  { path: '**', component: PageNotFoundComponent },

04 | Routing

From Template:

<a [routerLink]="['/signup']">Click here to Signup</a>

From your .ts file (typescript):

// src/app/landing/landing.component.ts
import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent {
  title = 'landing page';
  constructor(private router: Router) {}

  launchHome(): void {
    this.router.navigate(['/home']);
  }
}

05 | Barrel Files for the rescue

One of the first things you will notice when you start working on it is, you have to write so many import statements. Gets worst, when you have to make 2 dedicated imports to get hold of 2 components sitting inside the same folder.

Well, this isn’t one of those where you blame at Angular! This is something to do with Typescript. The resolution is to use barrel files. As a practice you can start creating an index.ts file in each of your folders containing services, components or feature modules.

Assume you src folder has too many components (example: Home, About, Contact):

The barrel file:

// src/app/index.ts
export { AppComponent } from './app.component';
export { HomeComponent } from './home.component';
export { AboutComponent } from './about.component';
export { ContactComponent } from './contact.component';

Usage:

import { AppComponent, HomeComponent, AboutComponent, ContactComponent} form './';

// or even simpler
import { * } from './';

There is a neat blog on this which can give you a better understanding of this.

06 | Running the App

ng serve

and navigate your browser to http://localhost:4200

07 | Unit Test and other CI/CD Concerns

There are scripts setup on package.json for these, one can refer it. For more on configuring karma & etc read this blog. Example, Running unit tests (jasmine – BDD):

ng test

08 | Need to create your feature module?

After sometime you realize your app module has grown out of proportion. It is time to consider some logical organization of your code. First is to consider organizing them into modules. Here is a neat read

09 | Adding a Simple Form

You will notice I’ve placed a simple form in ContactComponent. At this point it’s important that you don’t forget to import FormsModule in your app.module.ts.

However, one thing you will notice there is a realtime representation of form data. It is quite useful for you to debug, it can be achieved with the following peace of markup:


    <form #form="ngForm">
      ...
    </form>

    <div>Formdata in realtime:
      <pre>{{ form.value | json }}</pre>
    </div>

10 | Lifecycle Hooks

Intention behind post was to have an Angular2 guide which would help one to start a project from scratch & take it all way to deployment. I haven’t covered much of Angular2 concepts or structs on this post for brevity & aligning with my intention to keep it super short. However, Lifecycle Hooks are a thing it can’t afford to miss. Angular2 provides 8 of them in total: ngOnInit, ngOnChanges, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy. Here is an example:

import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
  constructor() {}

  ngOnInit() {
    console.log('App Component Init');
  }

  ngOnDestroy() {
    console.log('App Component Destroyed');
  }
}

You can refer this blog if you want to know them in detail

11 | Before you go for Production

You are just a command away if you want to do a production build for your awesome app. Afterwards you just need to copy the generated dist folder to your live server.

ng build --aot --environment prod

Yet, there are few things one should know going to this step. When you execute above the step there are so many things happening behind the scene. Here are some, concatenation, minification, uglification & tree shaking.

Since I have already made a note on first 3 on a different blog, I would like you to come to terms with Tree Shaking.

Tree Shaking is the process of getting rid of dead code. If you’re coming from Java world or most other OOP environments, you will be familiar with a warning called ‘unused code/method’. However, if you want to go deep into it with examples & numbers here is great post from an expert. Minko Gechev is the author of the official Angular Style Guide.

If you are already an expert at Angular & came across this post whilst considering ways to improve the page load time & performance tuning for your app here is a great stack overflow thread which you shouldn’t miss!

12 | Sourcecode

Here is the github repo used for this post.

oauth client

A boilerplate code

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="author" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> -->
  <link rel="stylesheet" href="index.css">
  <!--[if lt IE 9]>
      <script src="//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
      <![endif]-->
  <link rel="shortcut icon" href="">
</head>
<body>

  <button onclick="hello('google').login()">google</button>
  <button onclick="hello('google').logout()">logout</button>
  <!-- SCRIPTS -->
  <!--
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
      -->
  <script src="hello.all.js"></script>
  <script>
    hello.init(
      {google: "516591458871-s6jr870dbt8ep543258oaaofsl3v189v.apps.googleusercontent.com"}
    );
  </script>

  <script>
    hello.on('auth.login', function (auth) {

      hello(auth.network).api('/me').then(function (r) {
        console.log(JSON.stringify(r));
        debugger;
        var lab = document.createElement("div");
        lab.id = "pic_and_greet";
        lab.innerHTML = '<img src="' + r.thumbnail + '" /> Hey ' + r.name + '<p>'+r.aboutMe;
        document.body.appendChild(lab);
      });
    });

    hello.on('auth.logout', function () {
      var lab = document.getElementById("pic_and_greet");
      if (lab != null) document.body.removeChild( lab );
    });

  </script>

</body>
</html>

Spin up a local server

# Simple Server (to test it locally): 
$ python -m SimpleHTTPServer 5000

# Following aren't required

# Chrome Disable Security: 
$ open -a Google\ Chrome --args --disable-web-security --user-data-dir

# install pip: 
$ sudo easy_install pip

# install virtualenv: 
$ pip install virtualenv virtualenvwrapper
Image

dynamically add/remove siblings

1. App.js

App = Ember.Application.create();

App.IndexRoute = Ember.Route.extend({
});

App.IndexController = Ember.Controller.extend({
  items: [{
    id: 1,
    name: 'Pizza'
  },
  {
    id: 2,
    name: 'Nachos'
  },{
    id: 3,
    name: 'Spaghetti'
  }],
  actions: {
    remove: function (item) {
      this.items.removeObject(item);
      for(var i = 0; i < this.items.length; i++) {
         var temp = this.items.objectAt(i);
         Ember.set(temp, "id", (i+1));
      }
    },
    add: function (index) {
      this.items.insertAt(this.items.length, {
        name: 'Hot Dogs',
        id: this.items.length+1,
      });
    },
    summary: function() {
      Ember.$('#sum').text(JSON.stringify(this.items));
    }
  }
});

App.ListContainerComponent = Ember.Component.extend({
  tagName: 'ul',
  items: [],
  actions: {
    onRemove: function (item) {
      this.sendAction('onRemove', item);
    },
    onAdd: function (item) {
      var insertAt = this.items.indexOf(item) + 1;
      this.sendAction('onAdd', insertAt);
    }
  }
});

App.ListItemComponent = Ember.Component.extend({
  tagName: 'li'
});

2. The Markup

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/2.1.0/normalize.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="//builds.emberjs.com/tags/v1.10.0/ember-template-compiler.js"></script>
    <script src="//builds.emberjs.com/tags/v1.10.0/ember.debug.js"></script>
  </head>
<body>
  <script type="text/x-handlebars" data-template-name="application">
  <h1>Ember Food</h1>
  {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="index">
    {{list-container items=items onRemove='remove' onAdd='add'}}
    <div id="sum" {{action 'summary'}}>Summary</div>
  </script>
  
  <script type="text/x-handlebars" data-template-name="components/list-container">
    {{#each items as |item|}}
      {{#list-item content=item label=item.id }}
        {{item.name}}
        <button {{action 'onAdd' item}}>+</button>
        <button {{action 'onRemove' item}}>-</button>
      {{/list-item}}
    {{/each}}
  </script>
  
  <script type="text/x-handlebars" data-template-name="components/list-item">
    {{label}} 
    {{yield}}
  </script>
</body>
</html>

Javascript

Lempel–Ziv–Welch (LZW) Compression in JS

// Decode LZW-encoded string
function lzwDecode(s) {
        var dict = {};
        var data = (s + "").split("");
        var currChar = data[0];
        var oldPhrase = currChar;
        var out = [currChar];
        var code = 256;
        var phrase;
        for (var i = 1; i < data.length; i++) {
            var currCode = data[i].charCodeAt(0);
            if (currCode < 256) {
                phrase = data[i];
            }
            else {
                phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
            }
            out.push(phrase);
            currChar = phrase.charAt(0);
            dict = oldPhrase + currChar;
            code++;
            oldPhrase = phrase;
        }
        return out.join("");
}

// Compress a string with LZW
function lzwEncode(s) {
        var dict = {};
        var data = (s + "").split("");
        var out = [];
        var currChar;
        var phrase = data[0];
        var code = 256;
        var i, l;
        for (i = 1, l = data.length; i < l; i++) {
            currChar = data[i];
            if (dict[phrase + currChar] != null) {
                phrase += currChar;
            }
            else {
                out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
                dict[phrase + currChar] = code;
                code++;
                phrase = currChar;
            }
        }
        out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
        for (i = 0, l = out.length; i < l; i++) {
            out[i] = String.fromCharCode(out[i]);
        }
        return out.join("");
}