11/27/16

Export angularjs module

What are submodules?

When you writing angularjs application it is a good pattern to divide your app to submodules which are included into the main module as following:


angular.module('mainApp',['myApp.version','myApp.view1','myApp.view2'])

So it will be easy for testing or develop various parts of the application without each part need to knowing about other parts.
The directory structure of application usually place each submodule into its own directory:

.
├── view1
│   ├── view1.ts
│   └── view1.html


One of submodule "main" files contains angular module declaration:

    angular.module('myApp.view1', [
      'myApp.version.interpolate-filter',
      'myApp.version.version-directive'
    ])


How to import submodule into main typescript file?

It appears you can import code file which have no "export" syntax at all:


  //NO EXPORT AT ALL!
    angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', ($routeProvider: angular.route.IRouteProvider) => {
      $routeProvider.when('/view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
      });
    }])

    .controller('View1Ctrl', [() => {
    }]); 

Now in the main file - you can still use import syntax to include this code
app.ts

import './view2/view2';


Hope you have fun reading...

11/17/16

Organizing Your Angularjs Typescript Project

In one of my previous posts i found how to compile typescript files to javascript and i was very happy with myself because of my success. Since then i had little more experience with typescript. And now i have a few more points to share:

Using Import In Your Typescript Project

I have noticed many angularjs and angular2 projects using Import syntax. That way they not need to compile each file separately, instead you can compile only main file while all other files included in it (like in less or sass)
For exapmle :
Instead put all the things in your JS app.js file


//OOOOOLD STUFF.. BLAHHH
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

In typescript, you can move the config logic to its own separate config.ts file:

 export function config($locationProvider: ng.ILocationProvider, $routeProvider: angular.route.IRouteProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.otherwise({redirectTo: '/view1'});
  };



and import it to app.ts main file:

/// 
import { config } from './config';///<--HERE
module angularSeed {
'use strict';

  // Declare app level module which depends on views, and components
  angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.version'
  ]).config(config)

}
 

Import Is ES6 Syntax (Not Typescript!)

So, if you need to transpile your code either from ES6 and from typescript - i cannot think about other tool than webpack.

Weeeebpaaaack....
Webpack supports ES6 natively and for get it to compile typescript you only need to include ts-loader:
 
var webpack = require('webpack');
var path = require('path');
module.exports = {
    context: path.join( __dirname, '/app'),
    entry: 'app.ts',
    output: {
        filename: 'app.js',
        path: path.join( __dirname, '/app')
    },
    resolve: {
        root: path.join( __dirname, '/app'),
        extensions: ['', '.ts', '.webpack.js', '.web.js', '.js']
    },
    module: {
        loaders: [//<-- TYPESCRIPT, COOOL
        // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.ts?$/, loader: 'ts-loader' }
        ]
    }
}

Of course you need to include this webpack.config.js file in your project And update package.json with too more entries:
 
    "typings": "^0.8.1",
    "webpack": "1.13.1",
 

Build The Project

Since we using webpack now for build the project, the command to compile will be:


node_modules/.bin/webpack
 

Hope you have fun reading...
Visit my cool REPO

11/7/16

Presentational VS Container Components In React

What are Container Components?

There is rule for writing good & clear code - single responsibility.
Each code unit should depend as less as possible on other components (Should to care only about its own business in a human terms).
Thus it is good practice to separate code to self-containing units

Container Components are components which contains the logic of the component. Usually it contains in its markup one or more presentational components.

Presentational components are "dumb" components - they take care only about look of some part of data.

Example

Here is searchbar component


//Search Bar
import React, { Component, PropTypes } from 'react';
import {Link} from 'react-router';

let ResultsList = ({results, loading}) => {
        
      let createItem = function(repo, idx) {
        return <li key={idx}><Link to={`/repo/${repo.owner.login}/${repo.name}`}>{repo.name}</Link></li>;
      };
      let list;
      if(results && !loading) {
        list = results.length==0  ? 'no items yet' : results.map(createItem);
      } else {
        list = <div className="loader">Loading...</div>;
      }
      return <ul className="results">{list}</ul>;
             
}
export default ResultsList;

This code better to be refactored into smaller sub (Presentational)components

Refactoring:



import List from './List'
import Loading from './Loading'
import NoItems from './NoItems'
let ResultsList = ({results, loading}) => {
        
      return (<div>
        <Loading loading={loading}/>
        <List results={results}/>
        <NoItems results={results} loading={loading}/>
      </div>);
             
}

Here you can see that instead place logic and markup in the same place I made ResultsList to be Container which contains Loading List and NoItems presentational components

see code in this repo

11/1/16

Make React Component Code Shorter

In previous posts we created SearchPage component


class SearchPage extends Component {
      constructor(props) {
        super(props)
      }

      handleSearchTextChange(txt) {
        this.props.loadResults(txt);     
      }

      render() {
        const {results, loading} = this.props;
       
        return (
          <div>
            <SearchBar onChange={this.handleSearchTextChange.bind(this)}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};   

This code is working but, is there a way to make it more nicer and also more shorter?

The answer is "Yes"

First lets get rid of redundant "handleSearchTextChange" method:


class SearchPage extends Component {
      constructor(props) {
        super(props)
      }
      /*   
      handleSearchTextChange(txt) {
        this.props.loadResults(txt);     
      }
      */
      render() {
        const {results, loading} = this.props;
       
        return (
          <div>//<-- instead of "this.handleSearchTextChange.bind(this)"
            <SearchBar onChange={ this.props.loadResults}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};

or, even more simplier, lets take advantage of ES6 destructing syntax:

class SearchPage extends Component {
      constructor(props) {
        super(props)
      }

      render() {
        const {results, loading, loadResults} = this.props;//<--  loadResults method is one of the props too
       
        return (
          <div>
            <SearchBar onChange={loadResults)}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};

React Trick

There is a way in react to write a component much shorter is it has no other methods except render :


let SearchPage = ({results, loading, loadResults}) => {  
  return (
    <div>
      <SearchBar onChange={loadResults}/>
      <ResultsList results={results} loading={loading}/>
    </div>
  );
}

Thats all,far much shorter !

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...