Wednesday, February 22, 2017

About Webpack

Webpack is a bundler of components. It helps to bundles images, javascript, css into desired set of output

Apart from this Web pack helps to send parameters to javascript transformation to convert packages for production or development mode of components.


Javascript Bundling

In a development environment, there will be lots of javascript file for each component or module. When we move those into production as is, it will have a performance impact. Browser can only make less than eight parallel connection or concurrent calls to a proxy/host. If we have more number of files that will result in delay in loading a page (after 8th request it waits for a request to be completed before it starts 9th requests).

Style Bunding

sass-loader, less-loader, style-loader are used to transform sass/less/css files to css.

Sample: 
  { test: /\.scss$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader") },
  { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }

Extract Text Plugin is used here to keep the CSS output in a separate file. We can define those in plugins

 plugins: [
    new ExtractTextPlugin("css/sample.min.css"),
    new webpack.optimize.UglifyJsPlugin({
       output:{
        beautify: false
      }},
    ),
    new webpack.NoErrorsPlugin()
  ],

React Transformation

Babel is used transform jsx to js. 

{ test: /(\.js|\.jsx)$/, include: path.join(__dirname, 'client'), loader: 'babel', query: { presets: ["es2015", "react", 'stage-1'] } },
  
Presets here is the list of plugins babel supports for transformation currently babel has stage-3.


Recommendations

  • Reduce the number of static files as much as possible on production environment. This can be easily achieved using WebPack
  • Have static files on a separate web application than the actual application and set expiration of static files desired duration so that it 
    • Increase the parallel connection for application
    • Take static files from cache
  • Minfication of javascript helps to reduce the size of the javascript file. This can be done by Webpack.UglifyJSPlugin.
    • Compress
    • Mangle (Transform all local variables into character variables dynamically)
    • Beautify (To reduce the white space)
    • Comments (To remove/preserve comments) 
    • These are the option available in WebPack Uglify JS Plugin
  • Images, Sprite-WebPack helps to create a sprite image from sets of images.
  • Use CDN for common javascript packages like Bootstrap, jQuery


Sample: https://github.com/hariram302/react-kickstart/blob/master/webpack.config.dev.js





NPM Package

NPM is package manager for JavaScript, NPM Manager helps us to find, store JavaScript packages. There are lots of open community building modules which helps to build application quickly. Any components build to be used by NPM requires a package.json, which helps us to define 
  • Name - Name of the package
  • Version
  • Dependencies - Packages which are required to consumed by the application
  • devDependecies - Packages required for development
  • OptionalDependecies - Packages required for development, these are marked as optional when we execute npm install. If the package is not available npm install will fail.
  • Scripts - To execute the command on package lifecycle


Sample Package.json for React Application

{
  "version": "1.0.0",
  "name": "testapp",
  "author": {
    "email": "hariram.p@gmail.com",
    "name": "Hariram P"
  } ,
  "private": true,
  "license": "MIT",
  "devDependencies": {
    "babel-loader": "6.2.4",
    "babel-core": "6.18.2",
    "babel": "6.5.2",
    "babel-preset-es2015": "6.9.0",
    "babel-preset-react": "6.11.1",
    "react": "15.2.1",
    "react-dom": "15.2.1",
    "webpack": "1.13.1"
  },
  "dependencies": {
   
  },
  "scripts": {
    "build": "webpack --config webpack.config.js --display-error-details"
  }
}

Wednesday, February 15, 2017

React Redux Form Validation

React Validation

React validation can be easily done using React Redux Validator which will help us to add validator a page with ease.

npm install react-redux
npm install redux-form


Field

Each field need to be decorated with Redux Form Field,

Mandatory fields are

  • name (Name will be used to add validation)
  • field (Control reference for Redux-Form control to get added into form control)
  • component (Rendering the control, binding Redex references, and error notification)
  • Decorated inside a form

React Field exposes input and meta object which contains, which can be used to display error messages

Input (which add's following client events)
  • onBlur
  • onChange
  • onDragStart
  • onDrop
  • onFocus

Meta: (Redux Form properties)
  • active
  • valid
  • touched
  • error
  • invalid
  • visited
  • form
  • error
  • dirty
  • autofilled
  • submitting
  • submitFailed
  • pristine


Custom Control decoration with Field

renderField = field =>
        <formfieldscontrol
            name="name"
            field={field.input}

<input
            {...this.props.field}
            name={this.props.name}

Input Control decoration with Field

<input
            name=
            {...field}

Redux Form

While exposing redux form ensure a unique form page name, validation method and warn message passed.

export default reduxForm({
  form: 'CustomerPage',                 // a unique identifier for this form
  validate: CustomerPageValidation,     // <--- div="" function="" given="" redux-form="" to="" validation="">
  warn: CustomerPageWarn                // <--- div="" function="" given="" redux-form="" to="" warning="">
})(CustomerPage);


Sample

https://github.com/hariram302/react-kickstart/blob/master/client/CustomerPage.js
https://github.com/hariram302/react-kickstart/

Saturday, February 11, 2017

How to setup Proxy Git Repository

Most commonly on Continous Integration, we need to take latest of npm packages which might not be a idle solutions.

The best way is to have a proxy repository which can help to do quick download of npm packages. There are two ways of doing
  1. Setting up GitHub Enteriprise using Couch DB which mimick actual git hub.
  2. Setting up a proxy which acts as a private git repo which can download only if the package is not available in proxy.

Sinopia

Sinopia is an application acts as a proxy GitHub, which uses express as web server.

Prerequisites

  • Node JS (NPM Package manager)
  • Python 2.x (above 2.5 and less than 3.0)

Recommend Action

  • Define Python path in System Environment variable.
  • Define npm and npm cache folder to specific folder instead of user profile folder. 

Setting up Sinopia

npm install sinopia -g sinopia 

This install in global packages under sinopia

Run sinopia from command prompt which starts the server in localhost: 4873

Accessing Sinopia

npm set registry http://localhost/4873 

Which register sinopia as npm repository, if we try to execute npm install for any other packes you will be able to see localhost:4873 is called to download package.

We will able to see the package download in sinopia command prompt. If the same package is download again in sinopia command prompt you will see no download

Changing port/Exposing to external machines

  • Open full.yaml add
  • listen: http://localhost:333/ to run on different port
  • listen: http://<serverip:333>/ to expose as server

Setting up Sinopia as Windows Service

  • Download WinSW and rename that as sinopia-winsw
  • Create a configuration file in c:\sinopia, named sinopia-winsw.xml with the following configuration xml sinopia sinopia sinopia node c:\sinopia\node_modules\sinopia\lib\cli.js -c c:\sinopia\config.yaml roll c:\sinopia\  
  • Ensure right folder is set for arguments and working directory.
  • sinopia-winsw.exe install
    • To install
  •  sinopia-winsw.exe start
    • To start the sinopia as windows services which can avoid command prompt need.
https://github.com/rlidwka/sinopia/wiki/Installing-As-a-Windows-Service

Sunday, January 22, 2017

Using GitHub on Visual Studio Code


GitHub

Well known online Repository, commonly used for open source projects. Which has Source code view, Web editing (even TFS does not support this), Wiki and defect tracking system. There are couple of most commonly used flow for production roll out.


Git Commands

These are some of commands commonly used in GitHub. Most commands are integrated with Visual Code itself.
  • Fork
  • Origin
  • Checkout
  • Fetch
  • Pull
  • Push
  • Merge
  • MergeTool
  • PullRequest

Fork, is to create a personal branch
Command: git fork https://github.com/<<orgnization>>/<<project>>.git
GitHub UI:   Click on Fork button on a repository, which will prompt “Where should we fork this repository” with profile and repository. Click username or profile to create personal branch. If there is fork available for the profile it will display personal branch and the repository branch.

Set Origin, is to set working directory for development
Command: git remote add origin https://github.com/<<organization>>/<<project>>.git

Pull, to get latest version from a branch
Command: git checkout –q
-q is to keep quite on
checkout git fetch
git pull

Push, to push changes to remote from local
Command: git commit –all –m
--all – is used to take all the changes or developer can specify a file name
-m is the description for the commit change
– f is to set commit description on a file git push

Merge, if there is no conflict on check-in git merge will be able to merge all changes between branches. If there is any conflict, we have to fix those conflict and push it again. Git Hub doesn’t have any UI merging tool to fix a conflict, GitHub appends the conflict with arrow notation which highlights what came-in and what was checked-in. From this developer can fix them manually. There are lots of merge tools available in market like kdiff3, IntelliJ IDEA and lot more.
Visual Studio can also be used a merge tool. Unfortunately Visual Studio Code does not support merging.

We can use Visual Studio 2015 to do merging in UI. Once conflicts are resolved locally, perform push command to push the changes to remote, which helps merge fork/branch to desired branch.


How to set Visual Studio 2015 as merge tool?

  • Open VS 2015, install GitHub Extension
  • Open Team Explore, Click on Settings
  • Click on Global Settings to define
    • User Name 
    • Email Address 
    • Merge Tool

    Or do the changes in Git .gitconfig file by adding these lines

    [user]
    name = xxx
    email = xxxx@xxx.xxx
    [merge]
    tool = vsdiffmerge
    [mergetool]
    prompt = true
    [mergetool "vsdiffmerge"]
    cmd = \"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\vsdiffmerge.exe\" \"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\" //m trustexitcode = true
    [mergetool "vsdiffmerge"]
    keepbackup = false
    [diff]
    tool = vsdiffmerge
    [difftool]
    prompt = true
    [difftool "vsdiffmerge"]
    cmd = \"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\vsdiffmerge.exe\" \"$LOCAL\" \"$REMOTE\" //t
    [difftool "vsdiffmerge"]
    keepbackup = false

    User name and email are defined which can be used as a default attributes for git commit and git push



    Setting up Development Environment using Visual Studio Code

    • Visual Studio Code by default supports GitHub integration
    • Fork a branch
    • Create a folder in local path, open the folder in Visual Studio Code and Initialize GitHub

    • Execute git origin to set working directory (Use personal branch instead of remote branch)
    • Reopen Visual Studio Code by default VS Code will be opened with master branch in VS Code which will be displayed on Task bar.
    • Click “master” Git Icon from task bar, which helps to checkout a branch to local folder.
    • Click “sync” on git repository to get latest version from remote.


    Check-in changes

    • After making necessary changes click on Git which show changes performed.
    • Click on Tick mark which help commit changes with label for the changes
    • Click on “sync” icon or push link from "..." icon to push and pull changes to remote.


    How to merge conflicts on pull request

    • Open folder from which check-in is performed.
    • Open command prompt (Please do not use Visual Studio Code for executing this as merge tool. Launch is not supported from VS Code)
    • Pull repository files from where conflict is happening, for e.g.,
    • git pull https://github.com/<<organization&gt&gt/<<project>>.git <<branch>>
    • On completion of pull request, conflicts will be available in working folder.
    • Execute merge, “git mergetool” which will launch for Visual Studio 2015 to resolve conflict.
    • Execute push, “git push” which will push the changes to remote.


    This will help to fix merge conflict on a pull request from personal branch or a branch to desired branch.


    Development Process in GitHub

    GitHub flow

    In this flow Master Branch, which always act as a production branch that keeps the production copy always. Feature Branch for the development branch There are two ways of committing changes.

    • Check-in without any code review (Most people doesn’t prefer for this)
      • Make necessary changes on branch
    • Check-in with code review, forking or branching is required before merging. This is done by protecting a branch
      • Branching is not recommended, as everyone can be able to see the branch and any one can check-in on the branch
      • Fork is a personal branch which will be visible only to you.
      • Make necessary changes on your fork.
    • Commit Changes
    • Pull Request, If code changes is done in personal branch, merge changes to feature branch
    • Once a branch is ready to be deployed, deploy the branch, if there is any issue in production then rollback production with master, and else merge branch changes to master. 
    • For more information: https://guides.github.com/introduction/flow/


    Git Flow

    In this flow there will be set of physical branch like

    • Master(Production Branch)
    • Development Branch
    • Feature Branch
    • Release Branch
    • Hot Fix Branch
    This flow is most commonly used in enterprise application development. Install “Gitflow/Git-flow-cheatsheet” application which will provide high level operation for Vincent Driessen's branching model. Create required set of Physical branches.

    How this works

    • Development is done at Development and Feature Branch
    • Once testing is done on a development/feature branch, source code will be merged to release branch.
    • Release ready validation is performed on release branch.
    • Changes on release branch will be merged into development branch.
    • Once release branch is ready to be deployed, deploy the release branch in production.
    • Merge Release branch with hotfix, if there is any issue in production, then rollback change with master.
    • If there is any issue in production after rollout, do the changes in hotfix branch and move changes to production from hotfix.
    • Merge changes from hotfix to development and release branch.
    • Once hotfix branch is stable, changes will be merged to master.
    • For more information https://github.com/nvie/gitflow http://danielkummer.github.io/git-flow-cheatsheet/


    Protect GitHub Branch

    • Open GitHub
    • Select Repository for which protection is to be defined.
    • Select Settings
    • Select Branches
    • In Protected Branches, select a branch to which protection is to be defined.
    • Check "Protect this branch", which helps to define protection policy for the branch
    • Require pull request review before merging 
    • Restrict the list of user can merge the changes 
    • Require status check, this can help to check status from external service before merge.
    • Enterprise edition Protection options
    • Open Source edition Protection options