Saturday, December 9, 2017

Setting up a simple HTTP Server for local web development

1. Install NodeJS from https://nodejs.org

2.  Install http-server npm package

npm install -g http-server

3. From command line, change to the directory containing your static web files (e.g. html, javascript, css etc) in the command line window, e.g:

cd \temp\website

4. Start the server from the website directory with following command line command.
http-server

Or run it with more more options
http-server [path] [options]

See http-server

5. The http-server will start and print the local http address where the website can be reached. It is typically http://localhost:8080. Open your browser and go to the address http://localhost:8080 and you should see the index file in your web site directory from Step 3.

Wednesday, October 25, 2017

Getting started with React in 5 minutes


Development Environment Setup

1. Install node.js. What you really need is npm that is installed as part of node.js.

2. Install create-react-app npm module globally. This npm modules contains scripts that set up a new app, ready for further development.

npm install -g create-react-app

3. Create a folder where you want to create your react apps

C:\> md react
C:\> cd react
C:\react>

4. Create an app

C:\react> create-react-app hello-react

5. Change to your new application directory

C:\react> cd hello-react

6. Now you can run the dev version of your app.

npm start

7. Build production optimized version of your app in the build subfolder.

npm run build

8. To run the production version, npm install a static server (need to do just once)

npm install -g serve

9. Run the production version of the app

serve -s build

10. To manage all the configuration scripts yourself (permanent for the app; cannot be reverted).

npm run eject

React-friendly Editors, IDEs and Tools

  • Visual Studio Code
  • Sublime Text
  • WebStorm
  • Chrome Extension for React

Tools under the hood

React development environment uses the following tools.
  • Babel - Transpiler to convert ES6 JavaScript to ES5 for a wider Web Browser compatibility
  • webpack module bundler - To create a single bundle of js from multiple files
  • express - http server for dev
  • serve-static - To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express
  • eslint - static analysis of code

Advanced State Management Module (optional)

  • Redux
  • Use redux-logger middleware for viewing state changes

npm - Node Package Manager

npm manages JavaScript packages (source code for modules).

npm gets the package from the repository at https://www.npmjs.com/

npm is installed as part of nodeJs installation. Think of nodeJs as the runtime for npm.

Install npm

Install the latest version of nodeJs. npm is installed as part of nodeJs.

Initialize npm config file

Go the application directory.

npm init

Creates package.json that contains packages installed by npm.

Install a package

npm install <packagename> --save

Creates a node_modules folder for the module source code.
--save makes an entry for the module in Package.json

Package.json

Package.json keeps track of all packages installed (their dependencies).

npm modules can re-installed/refreshed by running:

npm install

We can create named scripts in the package.json

script {
   "start" : "<command line>"

The script can then be invoked as:
npm run <namedscript>

npm run build
npm run start

This is useful for builds and for starting the application.

App code sharing

When sharing code that uses npm packages, do NOT share node_modules folder. Simply share your js code and package.json. Running the the following command installs all the packages specified in package.json.

npm install

Global vs Local Modules

npm modules are usually installed local to an application (folder). This is preferred to avoid any breaking changes to modules.

Modules can be installed globally. This is usually done for dev tools that are utilized for multiple projects. For example, nodemon module that detects and restarts an application (web server) may be installed globally. nodeman re-executes a script or restarts the web server when underlying source code is changed.

npm install -g nodeman

To find the location of the global npm module folder:
npm root -g

To remove a global module.
npm remove -g nodeman

Useful Commands

Check npm version

npm -v
npm --version

Get help

npm
npm help
// overview
npm help npm

Initialize npm

npm init

// answer yes to all questions
npm init --yes 

// set / get / delete initialization defaults
npm config set <value-name-from-package.json> "default value"

npm config get <value-name-from-package.json>

npm config delete <value-name-from-package.json>

Install/Uninstall modules

// install module and update package.json
npm install lodash --save

// development only package install
npm install <package-name> --save-dev

// install a module globally
npm install -g <packagename>

// get (refresh) ALL packages in package.json
npm install

// get production-only packages in package.json
npm install --production

// uninstall a package - delete from module folder and package.json
// remove and rm are synonyms for uninstall
npm uninstall <packagename>

To remove a global module.
npm remove -g <packagename>

// install a specific version of a package
npm install <packagename>@version --save

// update to the latest version
npm update <packageversion>

If the version specified in the package starts with:

^1.2.3 Update to the latest minor version. Retain the major version.
~1.2.3 Update to the latest patch. Retain the major and minor version
* Update to the latest version

To specify update to a specify version of module, enter the specific version and do not precede the version with any of the characters above. Example: "1.2.3"

1.2.3
1 is major version
2 is minor version
3 is patch version

Listing installed modules

// list all packages and their dependencies
npm list

// list top level packages only
npm list --depth 0

Executing JavaScript Code

JavaScript can be run in a Web Browser

For example, in Google Chrome

1) Start Browser

2) Press F12 to open Developer tools

3) JavaScript code can be entered and run from either the following tabs.

  • Console
  • Sources | Snippets

JavaScript can be run from Command Line (Terminal)

1) Install nodeJs

2) Create a js file, for example app.js

3) Run the js file

node app.js

Website hosted JavaScript REPL

See: https://jsfiddle.net/

Saturday, October 21, 2017

JavaScript ES2015 ES6 Module Support

ES6 lets you natively define and use modules.

Since most Web Browsers do not currently support this feature, the code must be transpiled into ES5 using a tool such as Babel. This must occur at build time as a development step.

The code is transpiled into AMD or CommonJS module format by the tool. The HTML source then references RequireJS/SystemJS that is used by the Browser to load the modules in the depedency order at runtime.

To avoid use of a runtime module loader (for efficiency sake), the code can be bundled using bundlers such as Webpack (AMD module format) or Browserify (commonjs module format; commonly used to package nodejs code for use in a Browser) as a development step. The development step takes the transpiled source code and creates one or more bundled js files that contains code in the module dependency order (hence eliminating the need for a runtime module loader).

Module Export Syntax

Export functions inline

// somefile.js
export function doSomething(doWhat){
}

export function printResults(){
}

// do not export a private function
function privateHelper(){
}

// export a variable
export var pi = 3.142

Export public functions with a declaration

// somefile.js
function doSomething(doWhat){
}

function printResults(){
}

function privateHelper(){
}

// export a variable
var pi = 3.142

// we are renaming printResults to print when exporting
// we are also exporting a variable (can do the same for classes)
// privateHelper is not a part of the Api
export { doSomething, printResults as print, pi}

Specify Default Export

// somefile.js
export function doSomething(doWhat){
}

// make printResults the default function exported out of this module
export default function printResults(){
}

function privateHelper(){
}

// export a variable
export var pi = 3.142

Module Import Syntax

// import all public functions from the module
// methods can be invoked on extModule, e.g. extModule.printResults()
import * as extModule from './somefile.js'

// selective import of functions
// functions are invoked as usual e.g. printResults()
import {doSomething, printResults} as extModule from './somefile.js'

// selective import of functions with an alias
// function are invoked with its alias e.g. print()
import {doSomething, printResults as print} as extModule from './somefile.js'

// import the default function as print()
import print from './somefile.js'

// import the default function and another function
// print() is exported as default, also import doSomething function
import print, {doSomething} from './somefile.js'

Friday, October 20, 2017

JavaScript Module Formats and Loaders

JavaScript Module Formats

How JavaScript code (function) is structured into a module that can be loaded by Module loader at runtime in correct dependency order. This is just a convention followed in plain js to form Modules.
  • AMD Format (Asynchronous Module Dependency) - primarily used in Browser js since it has the advantage of being async loading. define function is used to load dependencies.
  • CommonJS Format - more prevalent in server (nodeJs) apps. require function is used to load dependencies.
  • Universal Module Definition (UMD) - Has both the features of AMD and CommonJS
  • System.register - Specific to SystemJS module loader
  • ES2015 - Native support in ES6 - Need to use something like Babel to use in current browsers

JavaScript Module Loaders

JavaScript libraries that load modules (specified in supported format) while honoring the dependencies.
  • RequireJS Module Loader can load modules in AMD Format
  • SystemJS Module Loader can load modules in CommonJS Format



Thursday, October 19, 2017

JavaScript Modules

Singleton Pattern

Immediately Invoked Function Expression (IIFE) returns an object that contains references to the public API of the module.

displayName function-scoped variable serves as the data member and retains its value as a result of function closure.

var myModule = (function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
})()

myModule.setName('Bob')
myModule.printName()

Hello Bob

Function Constructor Pattern

MyModule is a reference to a function closure. It is not immediately invoked. It still returns an object that contains references to the public API of the module. We can create multiple instances of this function using the new keyword. Each instance maintains its own state (displayName in this case).

var MyModule = function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
}

myModule = new MyModule
yourModule = new MyModule
myModule.setName('Jack')
yourModule.setName('Diane')
myModule.printName()
yourModule.printName()

Hello Jack
Hello Diane

// Same as above but using prototype for efficiency
// (function definitions are not duplicated for each instance)
var MyModule = function(){
    var displayName
}

MyModule.prototype.setName = function setName(name){
    this.displayName = name
}

MyModule.prototype.printName = function printName(){
console.log('Hello ' + this.displayName)
}

myModule = new MyModule
yourModule = new MyModule
myModule.setName('Jack')
yourModule.setName('Diane')
myModule.printName()
yourModule.printName()

Hello Jack
Hello Diane