Monday, May 8, 2017

Integrating ReactJS, Typescript, and Webpack Part 2

For those of you who want to dive in and see the final version of the code, check it out here!

ReactJS is a library released by Facebook and unlike other JavaScript frameworks out there (i.e. Angular, Backbone, Ember, etc), it’s goal is to simply represent the 'View' layer in the traditional Model View Controller (MVC) paradigm.

ReactJS, Typescript, and Webpack
Now that we have a Typescript and Webpack integrated on previous chapter Part 1, let's go ahead and throw ReactJS into the mix as well. Let's first NPM install ReactJS as a dependency.
  npm install --save react react-dom
Since we're using a 3rd party library with Typescript, we're going to need to NPM install Typings as well. You might be asking, "what is Typings?". Typings is simply the tool we use to manage all of the Typescript definition files. It’ll allow us to easily download and use all of our 3rd party Typescript definition files.
 npm install --save-dev typings
Here’s how our package.json file looks now:
{
  "name": "typescript-webpack-react",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "ts-loader": "^2.0.3",
    "typescript": "^2.3.2",
    "typings": "^2.1.1",
    "webpack": "^2.1.0-beta.22"
  },
  "dependencies": {
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  }
}
Let's download the Definitely Typed files for React and ReactDOM. We'll use Typings to do the installation:
 node_modules/.bin/typings install --save react react-dom

A couple of things to notice:
1. Because we didn't install Typings globally, we had to prefix the command with where the Typings module is located: node_modules/.bin/typings.
2. The "--save" flag indicates that we want to save the React and ReactDOM definition files.
3. Notice that our directory now has a typings directory as well as a "typings.json" file. The typings.json file specifies all of the definition files we have installed, and the typings directory contains the actual definition files.

Now that we're trying to use React with Typescript, we should update a Typescript configuration file tsconfig.json which we have set up on Part 1.
{
    "compilerOptions": {
        "jsx": "react",
        "module": "commonjs",
        "noImplicitAny": true,
        "outDir": "./build/",
        "preserveConstEnums": true,
        "removeComments": true,
        "target": "ES5"
    },
        "exclude": [
         "node_modules"        
    ]
}

A couple of things to note here:
1. Make sure that tsconfig.json is located in the root directory.
2. If you want to learn more about the tsconfig.json file, check this out. Of particular importance to us is the "jsx" key which tells Typescript to accept React’s JSX syntax whenever we create a file with a ".tsx" extension.
3. Notice that we’re specifying files and directories to include from going through the Typescript compiler.

Since we're using React now, let’s rename our src/some_module.ts file to src/Hello.tsx, and create a simple Hello component:
// Remember to rename your file to Hello.tsx and
// place it within your src/ directory

import * as React from "react";

interface HelloProps {
  name: string;
}

class Hello extends React.Component<HelloProps, {}> {
  render() {
    return <div>Hello, {this.props.name}</div>;
  }
}

export default Hello;
Let’s also rename our src/app.ts file to src/app.tsx, and change the content to the following:

// Remember to rename the file from app.ts to app.tsx
// and to keep it in the src/ directory.

import * as React from "react";
import * as ReactDOM from "react-dom";
import Hello from "./Hello";

ReactDOM.render(
  ,
  document.getElementById("root")
);
Since we’re injecting our rendered Hello component into the DOM, we’ll need to modify our index.html file as well.
<--index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Getting Started with Typescript, Webpack, and ReactJS </title>
  </head>
  <body>
<!-- this is where our Hello component will get rendered into -->
    <div id="root"></div>

    <script src="build/bundle.js"></script>
 </body>
</html>
We’ve renamed our application's entry point, which means we'll need to modify our webpack.config.js file as well. It's a minor change — we just need to change it to the correct file extension.
var path = require("path");

var config = {
  /*
   * app.tsx represents the entry point to your web application. Webpack will
   * recursively go through every "require" statement in app.ts and
   * efficiently build out the application's dependency tree.
   */
  entry: ["./src/app.tsx"],

  /*
   * The combination of path and filename tells Webpack what name to give to
   * the final bundled JavaScript file and where to store this file.
   */
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "bundle.js"
  },

  /*
   * resolve lets Webpack now in advance what file extensions you plan on
   * "require"ing into the web application, and allows you to drop them
   * in your code.
   */
  resolve: {
    extensions: ["", ".ts", ".tsx", ".js"]
  },

  module: {
    /*
     * Each loader needs an associated Regex test that goes through each
     * of the files you've included (or in this case, all files but the
     * ones in the excluded directories) and finds all files that pass
     * the test. Then it will apply the loader to that file. I haven't
     * installed ts-loader yet, but will do that shortly.
     */
    loaders: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        exclude: /node_modules/
      }
    ]
  }
};

module.exports = config;
And if you run "npm run build" in your terminal again, you should see Webpack do its thing and generate a new bundle.js file. If we open our index.html in the browser, you'll see the fruits of your labor!

Conclusion
Hopefully you've found this tutorial helpful for getting you started using these 3 technologies together. There’s tons more you can do (i.e. use webpack-dev-server, set up source maps in Typescript, etc) but I’ll leave it for you to continue exploring!

Source: Getting Started with ReactJS, Typescript, and Webpack

Friday, May 5, 2017

Getting Started with Typescript and Webpack Part 1

In this tutorial, I want to briefly describe Typescript and Webpack technologies and how to get started using both of them together. So let's get started!

Typescript is developed and maintained by Microsoft and it’s best described as JavaScript with an optional Type system. It’s a complete superset of JavaScript, which means that every bit of JavaScript code you’ve written is already valid Typescript code.

Webpack is a module bundler, and this simply means that it can take many different JavaScript files / modules and efficiently combine them together into one final JavaScript file.

For those of you who want to dive in and see the final version of the code, check it out here!

Typescript and Webpack

Let's go ahead and open a terminal window, create a new project directory, and cd into it.
Next, let's create the following directory structure inside of the project.
At the root of your project directory, run "npm init -y" which is a NPM command that creates a boilerplate package.json file for you.
Next, we'll install Typescript and Webpack. Notice that I installed Typescript and Webpack beta version with the " — save-dev" flag, which simply means that I want to save these packages as developer dependencies (i.e. these are packages that the actual web application doesn’t need but are used by developers to produce the final web application).
   npm install --save-dev typescript webpack@2.1.0-beta.22
Here’s how my package.json file and root directory look right now.
  {
   "name": "typescript-webpack",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^2.3.2",
    "webpack": "^2.1.0-beta.22"
  }
}
In order to set up Webpack, I'll add a webpack.config.js file in the root directory and it’ll have the following content:
var path = require("path");

var config = {
  /*
   * app.ts represents the entry point to your web application. Webpack will
   * recursively go through every "require" statement in app.ts and
   * efficiently build out the application's dependency tree.
   */
  entry: ["./src/app.ts"],

  /*
   * The combination of path and filename tells Webpack what name to give to
   * the final bundled JavaScript file and where to store this file.
   */
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "bundle.js"
  },

  /*
   * resolve lets Webpack now in advance what file extensions you plan on
   * "require"ing into the web application, and allows you to drop them
   * in your code.
   */
  resolve: {
    extensions: ["", ".ts", ".tsx", ".js"]
  },

  module: {
    /*
     * Each loader needs an associated Regex test that goes through each
     * of the files you've included (or in this case, all files but the
     * ones in the excluded directories) and finds all files that pass
     * the test. Then it will apply the loader to that file. I haven't
     * installed ts-loader yet, but will do that shortly.
     */
    loaders: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        exclude: /node_modules/
      }
    ]
  }
};

module.exports = config;

Next, let's install ts-loader by executing npm install ts-loader (remember to save it as a developer dependency).
 npm install ts-loader --save-dev
We’re almost there — now we just need to create a couple of files: index.html, src/app.ts, and src/some_module.ts
<--index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Getting Started with Typescript, Webpack</title>
  </head>
  <body>
    <script src="build/bundle.js"></script>
 </body>
</html>
// app.ts

import greeting from "./some_module";

console.log(greeting);
// some_module.ts
const greeting: string = "Hello World!";

export default greeting;
Now that we’re trying to use Typescript, we should create a Typescript configuration file in the root directory — be sure to name it tsconfig.json.
{
    "compilerOptions": {       
        "module": "commonjs",
        "noImplicitAny": true,
        "outDir": "./build/",
        "preserveConstEnums": true,
        "removeComments": true,
        "target": "ES5"
    },
        "exclude": [
         "node_modules"     
    ]
}
We'll also want to modify our package.json to include a NPM script which runs Webpack for us. Added a "build" script to the package.json file. Here's how my package.json file and project directory look right now.
{
  "name": "typescript-webpack",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "ts-loader": "^2.0.3",
    "typescript": "^2.3.2",
    "webpack": "^2.1.0-beta.22"
  }
}
We're finally here — the moment of truth! If we run "npm run build" in our root directory, we should see Webpack do its magic and produce a bundle.js file in the build directory. If we open the index.html file and look at the console, we should see our greeting "Hello World!" as below.


In next tutorial, We integrate ReactJS to the typescript and webpack. Click Integrating ReactJS, Typescript, and Webpack Part 2. to continue reading.

For those of you who want to dive in and see the final version of the code, check it out here!

Source: Getting Started with ReactJS, Typescript, and Webpack

Tuesday, February 28, 2017

How To Detect HTTP Or HTTPS in JavaScript?

You can use location.protocol to detect the protocol that the site is using. Lets say we have the url https://www.example.com. We can use following code to detect if it has HTTP or HTTPS.
console.log(location.protocol);
//output => https:

You can change the protocol of the site simply by using following logic:
var protocol = location.protocol === 'https:' ? 'http' : 'https';

console.log(protocol);
//output => http

How to solve nodejs Error: listen EADDRINUSE?

In this post we are going to discuss about how to solve Node.js error: listen EADDRINUSE. EADDRINUSE actually means that the port number which you are binding to the server using listen() is already in use.

If any application is already running on 3000 then you will get the below error (Error: listen EADDRINUSE). Here is the screenshot of error:

To solve this error either you start your node server on another port or close the program using that port. If you use lsof, you can see what process is bound to the port with lsof -i:3000, and then force kill it by grabbing the process id (aka pid) and kill it with a kill -9 $pid.

You'll only see it if you have permissions; if you're running lsof as a different user than the app, try prefixing lsof -i:$port with sudo to make sure you have adequate permissions.

Ref: https://teamtreehouse.com/community/hi-its-throwing-an-error-listen-eaddrinuse-3000-unhandled-error-event

Monday, February 13, 2017

What New ES6/7 Has To Offer?

This post will give you a quick introduction to ES6 (aka ECMAScript 2015). If you don't know what is ES6, it’s a new JavaScript implementation. If you haven't taken a look at ES6/7 yet you're missing out on some amazing advances to the JavaScript language.

Some of the important features of ES6/7 are below:
• let, const
• Template Strings/literals
• Arrow Functions
• Classes
• Destructuring
• Modules
• Native Promises
• Async Await
• Spread Operators
• Rest Parameters

Let + Const
In ES5, you declare variables via var. Such variables are function-scoped, their scopes are the innermost enclosing functions. In ES6, you can additionally declare variables via let and const. Such variables are block-scoped, their scopes are the innermost enclosing blocks.

let is the new var and block-scoped: they only exist in the block they are defined in.
var num = 0; //globally scoped

for (let i = 0; i < 10; i++) { //i is block scoped
  num += i;
  console.log('value of i in block: ' + i);
}

console.log('Is i defined here?: ' + (typeof i !== 'undefined')); //Is i defined here?: false 

Constants (also known as "immutable variables"), i.e., variables which cannot be re-assigned new content. const is single-assignment. const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards.
const foo;
    // SyntaxError: missing = in const declaration

const bar = 123;
bar = 456;
    // TypeError: `bar` is read-only

Template Strings/literals
Template literals are a new feature in ES6 to make working with strings and string templates easier. Template strings provide syntactic sugar for constructing strings. You wrap your text in `backticks` and you'll get the features described below.
• They can be multi-line. Finally!
• You can interpolate variables in them
• You can actually interpolate using any kind of expression, not just variables
• You can construct raw templates that don't interpret backslashes
// Basic literal string creation
`This is a pretty little template string.`

// Multiline strings
`In ES5 this is
 not legal.`

// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Unescaped template strings
String.raw`In ES5 "\n" is a line-feed.`

var today = new Date()
var text = `the time and date is ${today.toLocaleString()}`
console.log(text)
// <- 'the time and date is 8/26/2015, 3:15:20 PM'



Arrow functions
Fat arrow functions, also known as just arrow functions are a brand new feature in ECMAScript 2015 (formerly ES6). Arrows are a function shorthand using the => syntax. Arrow functions serve two main purposes: more concise syntax and sharing lexical this with the parent scope. Arrow functions behave differently than traditional JavaScript functions in a number of important ways:
• Lexical this binding – The value of this inside of the function is determined by where the arrow function is defined not where it is used.
• Not newable – Arrow functions cannot be used a constructors and will throw an error when used with new.
• Can’t change this – The value of this inside of the function can’t be changed, it remains the same value throughout the entire lifecycle of the function.
var reflect = value => value;

// effectively equivalent to:

var reflect = function(value) {
    return value;
};
When there is only one argument for an arrow function, that one argument can be used directly without any further syntax. The arrow comes next and the expression to the right of the arrow is evaluated and returned. Even though there is no explicit return statement, this arrow function will return the first argument that is passed in.

If you are passing in more than one argument, then you must include parentheses around those arguments. For example:

var sum = (num1, num2) => num1 + num2;

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
};

The sum() function simply adds two arguments together and returns the result. The only difference is that the arguments are enclosed in parentheses with a comma separating them (same as traditional functions).

When you want to provide a more traditional function body, perhaps consisting of more than one expression, then you need to wrap the function body in braces and explicitly define a return value, such as:
var sum = (num1, num2) => { return num1 + num2; }

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
};
You can more or less treat the inside of the curly braces as the same as in a traditional function with the exception that arguments is not available.

Because curly braces are used to denote the function’s body, an arrow function that wants to return an object literal outside of a function body must wrap the literal in parentheses. For example:
var getTempItem = id => ({ id: id, name: "Temp" });

// effectively equivalent to:

var getTempItem = function(id) {

    return {
        id: id,
        name: "Temp"
    };
};
The concise syntax for arrow functions also makes them ideal as arguments to other functions. For example, if you want to sort an array using a custom comparator in ES5, you typically write something like this:
var result = values.sort(function(a, b) {
    return a - b;
});
That’s a lot of syntax for a very simple procedure. Compare that to the more terse arrow function version:
var result = values.sort((a, b) => a - b);
The array methods that accept callback functions such as sort(), map(), and reduce() all can benefit from simpler syntax with arrow functions to change what would appear to be more complex processes into simpler code.

Classes
ES6 Classes formalize the common JavaScript pattern of simulating class-like inheritance hierarchies using functions and prototypes. They are effectively simple sugaring over prototype-based OO, offering a convenient declarative form for class patterns which encourage interoperability. Classes support prototype-based inheritance, constructors, super calls, instance and static methods.
class someClass {
    constructor(name, age) {
        this.name = name;
        this.age = age;
 }

    sayName() {
        alert(this.name);
    }

    sayAge() {
        alert(this.age);
    }
}

var myInstance = new someClass('dwayne', 27);
myInstance.sayName();
Class inheritance
class Child extends someClass {
    constructor(name, age) {
        super(name, age);
    }
    
    // Override the someClass method above
    sayName() {
        // This will call someClass.sayName() triggering the old alert
        // Which will just display our name
        super.sayName();
        
        // This will trigger the new alert which has labels and our age
        alert('Name:' + this.name + ' Age:' + this.age);
    }
}

var myChild = new Child('dwayne', 27);
myChild.sayName();
As you can see, classes are extremely flexible especially when extending a base class and having the ability to easily override a parent method without needing to write any boilerplate logic to do so.
In the ES6 classes syntax we have access to a function called super() which essentially just calls the parent function depending on the context and then returns the result. Calling super.parentMethodName() from within a child class will call the base class you inherited.

Destructuring
Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

/*Destructuring objects*/
const obj = { first: 'Jane', last: 'Doe' };
const {first: f, last: l} = obj;
    // f = 'Jane'; l = 'Doe'

// {prop} is short for {prop: prop}
const {first, last} = obj;
    // first = 'Jane'; last = 'Doe'


/*Array destructuring*/
const iterable = ['a', 'b'];
const [x, y] = iterable;
    // x = 'a'; y = 'b'


// list matching
var [a, ,b] = [1,2,3];
a === 1;
b === 3;

Modules
ES6 is the first time that JavaScript has built-in modules. In ES6 each module is defined in its own file. The functions or variables defined in a module are not visible outside unless you explicitly export them. This means that you can write code in your module and only export those values which should be accessed by other parts of your app.

ES6 modules are declarative in nature. To export certain variables from a module you just use the keyword export. Similarly, to consume the exported variables in a different module you use import.

Let's create a simple module that has two utility functions:
1. generateRandom() : Generates a random number.
2. sum() : Adds two numbers.

Next, let's create a file named utility.js for the module:
//utility.js

 function generateRandom() {
    return Math.random();
 }

 function sum(a, b) {
    return a + b;
 }

 export { generateRandom, sum }
That's it! The export keyword on the last line exports the two functions. As you can see, the exported functions are listed in curly braces separated by a comma. You can also rename the values while exporting like this:
 export {generateRandom as random, sum as doSum}

Now, let’s see how to consume the exported values in a different module.
//app.js

 import { generateRandom, sum } from 'utility';

 console.log(generateRandom()); //logs a random number
 console.log(sum(1, 2)); //3
Note the first line. This imports the exported values from the module utility. If you want to import a single value (for example sum), you can do it by writing the following:
import { sum } from 'utility';

You can also import the entire module as an object and access exported values as properties. So, we can modify our code as following:
 import 'utility' as utils;

 console.log(utils.generateRandom()); //logs a random number
 console.log(utils.sum(1, 2)); //3
Rest of the topics are coming soon.

References: Understanding ECMAScript 6 arrow functions
Learn ES2015
http://exploringjs.com/es6/index.html
ES6 Template Literals in Depth
Understanding ES6 Modules