ES6 – AppDividend https://appdividend.com Latest Code Tutorials Mon, 18 Mar 2019 08:59:14 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png ES6 – AppDividend https://appdividend.com 32 32 ReactJS Tutorial For Beginners 2017 From Scratch https://appdividend.com/2017/08/22/reactjs-tutorial-beginners-2017/ https://appdividend.com/2017/08/22/reactjs-tutorial-beginners-2017/#comments Tue, 22 Aug 2017 19:12:41 +0000 http://localhost/appdividend/?p=917 ReactJS Tutorial For Beginners 2017 From Scratch

ReactJS Tutorial For Beginners 2017 is the course we are covering today. There are many JavaScript Frameworks are there, which you can include in your next big project. Some folks are also stuck with the jQuery, and that is not a bad choice. If your project has any requirement that leaves you to use the […]

The post ReactJS Tutorial For Beginners 2017 From Scratch appeared first on AppDividend.

]]>
ReactJS Tutorial For Beginners 2017 From Scratch

ReactJS Tutorial For Beginners 2017 is the course we are covering today. There are many JavaScript Frameworks are there, which you can include in your next big project. Some folks are also stuck with the jQuery, and that is not a bad choice. If your project has any requirement that leaves you to use the Latest JS Frameworks then and then you have to use it otherwise no need in web development to get things more complicated. Today we are focusing on React.js, which is a wildly popular JavaScript library for a web application. It is the front-end framework to build user interfaces. So let us get started Learning ReactJS

Learning Everything In Web Development Is Today’s Necessity. You Can Not Escape It. If You Miss, You Will Soon Be Out Dated.
You do not need to be a sheep follower if, you do not need any Front End Framework or library.  First, analyze the requirement of any web application and if the application seems to be very large then and then you decide to go to Front end Framework or library. If Facebook is using it, then it does not mean we have to use it. Facebook has so many algorithms to manage the data and display it to every user, that is why they are using it.

Why should I learn ReactJS

If you find your application needs React.js then you use it, but for that, you have extensive knowledge about the framework, and if not then at least basic understanding is necessary. Some developers are learning during the project development face. Here are some honorable reasons to learn React.js.

  1. It is only the V or View part of MVC Architecture. While AngularJS is the MVC Framework. So, React.js is depended upon a State of the applications. The state is the actual Data.
  2. If you are using React.js with Redux, then you will understand the power of Functional Programming Language. So state modifications are done in an immutable manner and can not change the state of our application directly and also log the application at any given point of time.
  3. Once, you are familiar with the JSX syntax then, you need to only worry about state changes and nothing else in the Frontend side, so if you have done programming in JavaScript especially in the ES6 version of it, then it might be easy for you to grasp.

Prerequisites of This Course

  1. Beginner’s Guide To Setup ES6 Development Environment

  2. Beginner’s Guide To Setup ReactJS Environment

The second article is optional if you are using create-react-app tool for creating a React.js application.

ReactJS Tutorial For Beginners

Right now, we are not building React.js environment from scratch. We are using one tool called create-react-app to set up the boilerplate. You can find more information in the following Github Link.

If you are following this article then, you should have Node.js installed in your local or in your server. So you have access to the NPM and also Yarn. If you are not familiar with Yarn, then stick with NPM.

Step 1: Install the ReactJS Tutorial For Beginners Project.

npm install -g create-react-app
You need to install this dependency as a global so, your terminal must be in Administrator Mode if you are using Windows or in MAC put the sudo before above command.

Then, type the following command to create an application folder.

create-react-app reactjs2017
Do not write project name in capital or any word in capital otherwise NPM will not initiate the process and project will not create.

Go to the project folder by cd command and start the development server by either of the following code.

npm start or yarn start

Development server will start at this URL: http://localhost:3000/

You will see like this: Welcome to React

By default, there are so many configurations handle by our application automatically like,

  1. Babel
  2. Webpack
  3. ESLint

We only focus on code and not the dev. environment. So it is straightforward for us just to code elegantly.

Our React.js version is v15.6.1

Step 2: Modify App.js file inside src folder.

Just replace following code with existing code that comes with the project.

// App.js

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        ReactJS 2017 Tutorials
      </div>
    );
  }
}

export default App;
Every component must be wrapped with one parent element. In most cases, it is div tag, but it can be anything.

Now, when you save the above code gets recompiled automatically and restart the server and page will also automatic refresh, and changes are showing clearly in the browser. So that is the power of the create-react-app tool. If you are violating the ES6 rules then also it will show you the warning the console or terminal.

If you are going to assign an HTML element to a particular class, then please note here that the attribute class name is replaced by className in React.js because of React.js reserve the class keyword.

Step 3: Creating our own component.

We can create React component in Two ways.

  1. Functional Approach
  2. Class Approach(Object Oriented Approach)

We are going to use Functional Approach First.

Create one file inside src folder called Dividend.js and put the following code in it.

// Dividend.js

import React from 'react';

const Dividend = () => {
  return (
    <div>
      Dividend Component
    </div>
  )
}
export default Dividend;

Here, I have used ES6 arrow function syntax. This file simply returns the Dividend component.

If you are using Functional approach then your function or component name must start with capital letter.

Now, we need to include this component into the src  >>  index.js file to render the changes in the browser.

Right now, our index.js file looks like this.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

By default, App.js component is rendering in the browser, but we need to change it to the Dividend.js

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Dividend from './Dividend';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Dividend />, document.getElementById('root'));
registerServiceWorker();

Now, if you will save the file and switch to the browser then you will see Dividend Component.

So, our component properly renders. So, this is the functional approach. But in real world scenario, this component are less suitable and class approach is more suitable.

We are creating the same component in class or object oriented approach.

// Dividend.js
import React, { Component } from 'react';

class Dividend extends Component {
  render() {
    return (
      <div>
        Dividend Component
      </div>
    );
  }
}

export default Dividend;

Step 4: Composing components in one another.

Now, we have one component called Dividend. If we want to include some dividend paying stocks list then, we surely do and finally, our only one component will render.

Generally, if we have lots of components, then we will create one folder inside src directory but, right now I am not creating any of this and just put all the components inside src directory. So create one component called DividendRow.js inside src folder.

// DividendRow.js

import React, { Component } from 'react';

class DividendRow extends Component {
  render() {
    return (
      <tr>
        <td>{this.props.name}</td>
        <td>{this.props.dividendYield}</td>
      </tr>
    );
  }
}

export default DividendRow;

Here, I have rendered the table rows component, but we have not created the table yet, first we need to create it and pass the data to this DividendRow.js component.

// Dividend.js

import React, { Component } from 'react';
import DividendRow from './DividendRow';

class Dividend extends Component {
  constructor(props){
    super(props);
    this.state = {
      lists: [
        {
          name: 'TCS',
          dividendYield: '0.4'
        },
        {
          name: 'Infosys',
          dividendYield: '0.5'
        },
        {
          name: 'HCL',
          dividendYield: '0.6'
        }]
    }
  }
  render() {
    return (
      <table>
        <thead>
            <tr>
            <td>Name</td>
            <td>DividendYield</td>
            </tr>
        </thead>
        <tbody>
          {this.state.lists.map(list => {
            return <DividendRow name={list.name} dividendYield={list.dividendYield} />
          })}
        </tbody>
      </table>
    );
  }
}

export default Dividend;

Here, I have initialized one state called lists and pass that list as a property or props to the Table Row component and use it. I have already included the DividendRow.js component and use it inside another component called Dividend.js. Finally, Dividend component will be exported and render in the browser.

In real time example, the states are either filled with AJAX data. When the data changes according to that components will react. That is why the library is called React.js.

So this is the really very basic example of ReactJS Tutorial 2017. If you want to learn more then please check out my another post and also stay tuned for my blog. There will be the advance topic of React.js will post soon.

The post ReactJS Tutorial For Beginners 2017 From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/08/22/reactjs-tutorial-beginners-2017/feed/ 4
Observables in RxJS https://appdividend.com/2017/04/25/observables-in-rxjs/ https://appdividend.com/2017/04/25/observables-in-rxjs/#respond Tue, 25 Apr 2017 12:35:05 +0000 http://localhost/final/?p=425 Observables in RxJS

Welcome back, web developers, In today’s AppDividend Tutorial, I have briefly described Observables in RxJS. Observables are pioneer concept in Reactive Programming. If you do not know what is Reactive Programming, then check out my article on this website  What is Reactive Programming in Javascript. We will see following topics in this article. What is an observable? Difference between Observable and Promise […]

The post Observables in RxJS appeared first on AppDividend.

]]>
Observables in RxJS

Welcome back, web developers, In today’s AppDividend Tutorial, I have briefly described Observables in RxJS. Observables are pioneer concept in Reactive Programming. If you do not know what is Reactive Programming, then check out my article on this website  What is Reactive Programming in Javascript.

We will see following topics in this article.

  1. What is an observable?
  2. Difference between Observable and Promise
  3. Difference between Array and Observable
  4. Creating an observable
  5. Unsubscribe from an observable

What is Observables

Observables are simply a data streams or collections which arrive at a time. Observables are objects that can notify subscribers when the change is happening. We can wrap Observables as an object which contains following things.

  1. Data Streams
  2. Some methods (next(), error(), complete())
Observables in RxJS
Observables in RxJS

Promises vs. Observables

If you do not know what promise is, check out my another article on this website called Promises in ES6Promises are a way of saying that till now I have not any data while in a pending state, but in future, It will surely either resolve or reject the data depending on the result. However, Promises are different from Observables. Let us take an example.

Example #1 (Promise)

//main.js

let prom = new Promise((resolve, reject) => {
   setTimeout(()=>{
      resolve('hello');
   },1000);
   console.log('Invoked Promise')
});

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file.

Output

Invoked Promise

That means, till now in above code, we have not invoked promise. Still, It will run and give us a logged statement. Now check the same for Observables.

Example #1 (Observable)

//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
    },2000)
    console.log('Invoked Observables');
})

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2.  RxJS library not found in this code snippet.
  3. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1. What is Reactive Programming in Javascript?  Follow this article strictly and put above code in the main.js file.

Output

// nothing will show up here

That means, Observables are lazy, We want to subscribe it to get the output from it, whereas Promises are not lazy.

//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
    },2000)
    console.log('Invoked Observables');
});
obs.subscribe();

Output

Invoked Observables

Arrays vs. Observables

Arrays vs.Observables
Arrays vs.Observables

Array elements do not relate to anytime. It just arrives, forms a Data Structure and we can apply some Higher Order Functions on it, and then we can get a new array.

Observables are entirely different from Arrays, as they arrive in various time, so all the elements behave like a data streams. So we can sum it up as Observables are data streams comes at a time. It return an object on which we can call next(), error() and complete() method on it.

Creating an Observable

// main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
    },2000);
});
obs.subscribe(data => console.log(data));

Output

hello

We have imported an observable library, and then we have created a new instance of an observable via invoking new keyword. We have passed the observer object to the constructor as a parameter. We have thrown a stream called ‘hello‘ via next() method on the observable so that when we subscribe to the observable, we get the data.

// main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
        observer.complete();
    },2000);
});
obs.subscribe(data => console.log(data),
            (error) => console.log(error),
            () => console.log('Done')
);

Output

hello
Done

If we call complete() method on an observable then, after all the collections have been done, it will fire done a callback, which accepts no argument but can assure that the stream of data is complete via subscribing the observer. So basically, subscribe() method has three callbacks

  1. We get original data via subscribing an observer.
  2. Error callback, if any error has been thrown from an observer.
  3. Complete callback invoked immediately if complete the data stream is completed.
//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        throw 'an error';
    },2000);
});
obs.subscribe(data => console.log(data),
            (error) => console.log(error),
            () => console.log('Done')
);

Output

Uncaught an error

Unsubscribe from an observable

//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello');
    },2000);
    return () => {
        console.log('Disposal called');
    }
});
let object = obs.subscribe(data => console.log(data),
            (error) => console.log(error),
            () => console.log('Done')
);
object.unsubscribe();

Output

Disposal called

We have unsubscribed the subscriber, and we no longer get the data. Instead, we got the confirmation that we have unsubsribed the data.

Memorable Points

  1. We want to make use of observables to handle, manage and compose asynchronous events.
  2. There are mainly three asynchronous events in a web browser 1) DOM Events 2) AJAX Requests 3) Animations. It can be used to model events, asynchronous requests, and animations.
  3. Observables represent push based async data source.
  4. It emits no data until consumer wants it.
  5. It can also be transformed, combined, and consumed using the Array methods like map(), filter(), reduce() and other higher order functions
If you still have doubt in this Observables in RxJS then ask in the comment below, I am happy to help you out.

The post Observables in RxJS appeared first on AppDividend.

]]>
https://appdividend.com/2017/04/25/observables-in-rxjs/feed/ 0
Generators in ES6 https://appdividend.com/2017/04/23/generators-in-es6/ https://appdividend.com/2017/04/23/generators-in-es6/#respond Sun, 23 Apr 2017 22:52:12 +0000 http://localhost/final/?p=419 Generators in ES6

Hello, web artisans, In today’s AppDividend Tutorial, I have briefly described Generators in ES6. Generators Generators are the entirely new flow of control. It allows you to pause of execution at any particular time, so it is very lazy but very powerful. Generators are also called Pausable Functions. So, a generator function can stop and be restarted, as many times as you want. Standard […]

The post Generators in ES6 appeared first on AppDividend.

]]>
Generators in ES6

Hello, web artisans, In today’s AppDividend Tutorial, I have briefly described Generators in ES6.

Generators

Generators are the entirely new flow of control. It allows you to pause of execution at any particular time, so it is very lazy but very powerful. Generators are also called Pausable Functions. So, a generator function can stop and be restarted, as many times as you want.

Standard Function

It takes an argument or not necessary and return a new value. Functions are a fundamental necessity in the programming language. When we call the functions, it will start execution, and we can not interrupt it until it has done. So we can not pause during its execution.

//main.js

let fun = hello => console.log(`${hello}, how are you`);
fun('hello');

Output

hello, how are you

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file.

Generator Functions

Syntax

function *hello(){
   // body
}

Or

function* hello() {
  //body
}

Example #1

//main.js

function* generate() {
   console.log(`hello`);
}
let gen = generate();
console.log(gen);

If you see in the console panel, the nothing will show up. So what happens to log statement. Well, don’t worry. That is how generators work. It is not working same as Functions are working. Generators return an Iterator, on which you call next() method. If you do not know, what is an Iterator, check out my another article on Iterators in Javascript

//main.js

function* generate() {
   console.log(`hello`);
}
let gen = generate();
console.log(gen.next());

So, generate() function will return an object on which you can call next() method. If you remember Iterator then, it will return an object containing two properties.

Object {value: undefined, done: true}

Now, you will understand that Generators are generating an Iterable object on which you can call all Iterator’s method like next().

Here in our example, the output will be the same as above snippet.

Output

Object {value: undefined, done: true}

Value property here is undefined. We can provide the values using various methods.

//main.js

function* generate() {
    yield 'krunal'
   console.log(`hello`);
}
let gen = generate();
console.log(gen.next().value);

Output

krunal

yield

In generators, communication happens in the both directions. You can pass the values into the generator function. The next() the method can take values to be assigned.

In the above example, we used a keyword called “yield“, what does its mean that we have assigned the value to the generator function. Above example, we have assigned ‘krunal‘ string value to the generator function. So in output of gen.next(), it will return the object containing the properties like {value: ‘krunal’, done: false}

We can also assign the generator value via passing the arguments to that generator function.

//main.js

function* generate() {
   let result = yield;
   console.log(result);
}
let gen = generate();
gen.next();
gen.next('krunal');

Output

krunal

Example #2

/main.js

function* generate() {
  yield 1;
  yield ['krunal','ankit','rushabh'];
}
let gen = generate();
console.log(gen.next().value);
console.log(gen.next().value);

Output

1
['krunal','ankit','rushabh']

In above example, we are yielding two values. That is why it will log the value one by one. Now, if we want to iterate the array, then we want to do following.

//main.js

function* generate() {
  yield 10;
  yield* ['krunal','ankit','rushabh'];
}
let gen = generate();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);

Output

10
krunal
ankit
rushabh

yield* behaves like an iterator, and we can iterate one by one and log the value in the console.

Example #3

//main.js

function* generate() {
  yield 10;
  yield 20;
  yield 30;
}
let gen = generate();
for(value of gen){
    console.log(value);
}

Here is the proof that generator generates an iterator. On iterator, we can iterate a for..of loop and log the values one by one.

generators in es6
Generators in es6

Memorable Points

  1. The generator generates an iterable object on which we can call the next() method, and we can take the control over a function.
  2. Generators are pausable and resumable functions as many times as you want.
  3. We can use generators to quickly cancel asynchronous operations.
  4. The generator function syntax is just like a regular function but with an asterisk(*) after the function keyword.
  5. When you call a generator function, it should not execute the function like a normal function but, it will return an object called an iterator.
  6. We can pass the argument via next() method and then yield resume the execution of a generator.
  7. yield* can also work as an iterator, and we can use the for..of loop over it.
If you still have doubt then ask in the comment below, I am happy to help you out.

The post Generators in ES6 appeared first on AppDividend.

]]>
https://appdividend.com/2017/04/23/generators-in-es6/feed/ 0
Promises in ES6 https://appdividend.com/2017/04/19/promises-in-es6/ https://appdividend.com/2017/04/19/promises-in-es6/#respond Wed, 19 Apr 2017 14:29:26 +0000 http://localhost/final/?p=406 Promises in ES6

Hello, web programmers, In today’s AppDividend Tutorial, I have briefly described Promises in ES6. Promises have arrived natively in ES6. It is also available in 3rd party libraries like fetch which is used in HTTP calls or AJAX calls, and also jQuery 3.0 now supports Promises. What is Promise As its name suggests, It will return a promise as an object of any particular asynchronous actions. Promises […]

The post Promises in ES6 appeared first on AppDividend.

]]>
Promises in ES6

Hello, web programmers, In today’s AppDividend Tutorial, I have briefly described Promises in ES6.

Promises have arrived natively in ES6. It is also available in 3rd party libraries like fetch which is used in HTTP calls or AJAX calls, and also jQuery 3.0 now supports Promises.

What is Promise

As its name suggests, It will return a promise as an object of any particular asynchronous actions. Promises are results of eventual operations, and it is Object. This object has three states.

  1. Pending State
  2. Fulfilled State
  3. Rejected State

I will explain you one by one state but first, let me tell you its syntax

Syntax

let promise = new Promise((resolve, reject) =>  {
        // here async actions are performed
        resolve('your result');
});

// in case of success
promise.then((resolve) => console.log(resolve));

//in case of fail or an error
promise.catch((reject) => console.log(reject));

In promise, we have to pass two arguments to its constructor

  1. resolve
  2. reject

At this point, we do not know whether the promise will resolve or reject because in asynchronous calls will take some milliseconds to execute the promises. Asynchronous calls are simply AJAX calls, which will take some time to execute and will get a response from the server. So by that time, the state will be pending.

Pending State

While the Asynchronous task is performed, the promise object is in the holding state which does not contain any value. Instead, it will return a promise that any point of time in future it will get either resolve or reject with any error. This state is called Pending state

Resolve or Fulfilled State

If the operation of the Asynchronous task is successfully completed, then It will be resolved, and you can get its value by calling then function on promise object.

let promise = new Promise((resolve, reject) =>  {
        resolve('hello world');
});
promise.then((resolve) => console.log(resolve));

In above example, I am not performing any asynchronous call just show you a syntaxial example.

Rejected State

If the operation of the Asynchronous task is not completed successfully and an error occurred or thrown, then It will be dismissed, and you can get error value by calling catch function on promise object.

let promise = new Promise((resolve, reject) =>  {
        reject('an error occured');
});
promise.then((reject) => console.log(reject));

Example #1

//main.js

let promise = new Promise((resolve, reject) =>  {
        setTimeout(() => {
            resolve('Promises are working')
        }, 2000);
});
promise.then((data) => {
    console.log(data);
});

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file.

Output

Promises are working //after 2 seconds

Here in above example, we have use setTimeout function to delay in output so that it will behave as an asynchronous task. After 2 seconds the promise will resolve and execute the then callback function which is accessible on the promise object. This callback has the data from returned from the Asynchronous Task. So, it is passed as an argument, and then we have the log that value and output will be above statement.

let promise = new Promise((resolve, reject) =>  {
        setTimeout(() => {
            reject('Aww there is something wrong')
        }, 2000);
});
promise.catch((error) => {
    console.log(error);
});

In this scenario, an Asynchronous task will give an error, and we can call catch method on promise object and take an argument as an error and log that error.

Output

Aww there is something wrong //after 2 seconds

Example #2

//main.js

let prom = () => {
    return new Promise((resolve, reject) =>  {
        setTimeout(() => {
            resolve(3);
            if(1){
                reject('error');
            }
        }, 1000);
    });
}
prom().catch(error => console.log(error));
prom().then(data =>console.log(data));

Output

3 //after 1 second

Here, first, we create a function that returns a promise and then depending on success or failure, we have called then() and catch() (methods respectively. If you close look at the example, whichever event occurs first like if the resolve() is called first then respectively then() method is called and if reject() method is called then respectively catch() method will be executed.

Callback Hell

Promises and Callbacks are pretty much the same but differ in one term called “Callback Hell.” If you compose more than two callbacks, then things get complicated, and you will end up with mess code. Promises are composable, so we can create multiple promises and pass it to only one function, and it will get either resolve or reject one by one and also it removes the callback hell problem.

Let’s take an example of what is called a callback hell.

//main.js

let mj = 'KingOfPop';
let prom = (data, callbackFunction) => {
    callbackFunction(null,data);
}
prom(mj, (error, data) => {
    console.log(data);
    prom(mj, (error, data) => {
        console.log(data);
        prom(mj, (error, data) => {
            console.log(data);
        });
    });
});

Output

KingOfPop
KingOfPop
KingOfPop

In above example, I have used callbacks instead of Promises. So the callback hell is created because first, we call prom function and then again when it completes, we called another and then another, so pyramid of doom is created which is also called callback hell. We can also get the same output using Promises.

//main.js

let prom = (data) => {
    return new Promise((resolve, reject) => {
        if(data){
            resolve(data)
        }
        reject('An Error occured');
    });
}
Promise.all([
    prom('KingOfPop'),
    prom('KingOfPop'),
    prom('KingOfPop')
]). then(data => data.forEach(d => console.log(d)));

KingofPop
KingOfPop
KingofPop

So, basically, we can compose multiple promises and then it will resolve or reject depending on the result. It is very cool. In above examples, I have not used Asynchronous Code because I am leaving it to you to perform faking ajax request or use timeout function on your own and see the magic.

Promises In ES6
Promises In ES6

Memorable Points

  1. Promises are a way of saying that till now I have not any data while in a pending state, but in future, It will surely either resolve or reject the data depending on the result.
  2. We can use multiple promises and compose it in a way that we can remove a callback hell problem.
If you still have doubt then ask in the comment below, I am happy to help you out.

The post Promises in ES6 appeared first on AppDividend.

]]>
https://appdividend.com/2017/04/19/promises-in-es6/feed/ 0
Callback in Javascript https://appdividend.com/2017/04/18/callback-in-javascript/ https://appdividend.com/2017/04/18/callback-in-javascript/#comments Tue, 18 Apr 2017 19:53:54 +0000 http://localhost/final/?p=369 Callback in Javascript

Hey, web geeks, In today’s AppDividend Tutorial, I have briefly described Callback in Javascript. In Javascript, Functions are objects. They are First Class Objects.  So, we can use as a variable like Strings and Objects. If they are variables, then we can do following with them. Passing functions as an argument to the function. Return function from a function. Storing the anonymous […]

The post Callback in Javascript appeared first on AppDividend.

]]>
Callback in Javascript

Hey, web geeks, In today’s AppDividend Tutorial, I have briefly described Callback in Javascript.

In Javascript, Functions are objects. They are First Class Objects. 

So, we can use as a variable like Strings and Objects. If they are variables, then we can do following with them.

  1. Passing functions as an argument to the function.
  2. Return function from a function.
  3. Storing the anonymous functions into the variables.

Callback in Javascript

A function that is passed to another function as an argument and the given function is executed inside the otherFunction. That parameterized function is called as Callback. We have used callbacks many times especially in jQuery where we listen from the DOM event and pass the callback to that function. For example

Example #1

jQuery("button").click(function() {
  alert("Clicked");
});

When we click the button at the same time click event is fired, and we pass the Anonymous Function as a parameter and that Anonymous Function is called Callback. In this example, click function’s argument is another function. So that another function is a callback. Wherever click event happens parameterized function will be executed, or in other words, the callback is executed.

We can also store the function into the variable like,

//main.js

let mj = () => {
    return 'mj';
}
console.log(mj());

In above example, we have stored the function into the variable called mj, and later we called it and then in a console, we can see “mj“. I have used arrow function which is new ES6 feature in Javascript 

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file.

Example #2

//main.js

let dance = (param) => {
    return `MJ is ${param}`;
}
let sing = (param) => {
    return `MJ is ${param}`;
}
let mj = (param, fn) => {
    return fn(param);
}
console.log(mj('singing', sing));
console.log(mj('dancing', dance));

Output

MJ is singing
MJ is dancing

In above example, first of all, we have defined two functions. dance() and sing().

Next, we have created one more function called mj(), which accepts two arguments.

  1. singing/dancing as a string
  2. Anonymous Function or Callback

Callback functions are none other than that previously defined two functions.

  1. dance()
  2. sing()

So, in our case dance() and sing() are callbacks.

Example #3

//main.js

setTimeout(()=> {
    console.log('1st');
    setTimeout(()=>{
        console.log('2nd');
        setTimeout(()=>{
            console.log('3rd');
        }, 1000);
    }, 1000);
},1000);

In above example, we have used the setTimeout event, which is Asynchronous and entirely dependent on a specified time interval. Here in also the setTimeout event accepts two parameters

  1. Anonymous Function
  2. Time(milliseconds)

At given time interval function is fired and log the statement.

Output

1st
2nd
3rd

Memorable Points

  1. One point to remember that we are not executing the function in the parameter, we are only passing the function definition. Parameterized function is executed inside the main function.
  2. If you have read my Closures article, insider function can access all the variables and properties of the outsider function. So, callbacks have access to an outer lexical scope. That means callbacks behaves as Closures too.
  3. Higher Order Functions is the second name of Callback functions because of their behavior like passing another function as an argument, return a function as a value from another function.
callbacks in javascript
Callbacks in javascript

In above figure, we do not always pass the second parameter as a value; I have just taken an example that there have been multiple anonymous functions as well as values can be passed the main function and later it will execute inside that function. It will always behave as a Closures.

If you still have doubt then ask in the comment below, I am happy to help you out.

The post Callback in Javascript appeared first on AppDividend.

]]>
https://appdividend.com/2017/04/18/callback-in-javascript/feed/ 2
Iterators in Javascript https://appdividend.com/2017/04/16/iterators-in-javascript/ https://appdividend.com/2017/04/16/iterators-in-javascript/#respond Sun, 16 Apr 2017 19:34:45 +0000 http://localhost/final/?p=348 Iterators in Javascript

Hey, web fellows, In today’s AppDividend Tutorial, I have briefly described Iterators in Javascript. Iterators in  Javascript An iterator is a new concept of ES6. An Iterator is an object that let us iterate through an Array, an Object, a String or even custom Objects. The Iterator allows us to effectively loop over a collection of objects like an array, string, objects or other data structures. Example //main.js let dances = ['Robot', […]

The post Iterators in Javascript appeared first on AppDividend.

]]>
Iterators in Javascript

Hey, web fellows, In today’s AppDividend Tutorial, I have briefly described Iterators in Javascript.

Iterators in  Javascript

An iterator is a new concept of ES6. An Iterator is an object that let us iterate through an Array, an Object, String or even custom Objects.

The Iterator allows us to effectively loop over a collection of objects like an array, string, objects or other data structures.

Example

//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next());

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file.

Output

Object {value: "Robot", done: false}

Weird right? However, that is the meaning of iterator. It provides us an interface on which we can call the method like next(). Further, that also return an object, which we store in a variable and then when we logged it into the browser we can see an object with the two properties

  1. value: It holds the next value of an iterator object.
  2. done: It is the flag that indicates that the items in the iterable object are not complete in the iterating process.
//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next().value);

Output

Robot
//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next().done);

Output

false
//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
console.log(mj.next());
console.log(mj.next());
console.log(mj.next());
console.log(mj.next());

Output

Object {value: "Robot", done: false}
Object {value: "Hip-hop", done: false}
Object {value: "break", done: false}
Object {value: undefined, done: true}

If you notice carefully, then the last object has value undefined and done is true. It means that our array has only three items and up to 3 items done is false because the compiler does not know that whether the next value is there or not so it gives the done = false. After that when next value is not there then it will give the value = undefined and done = true.

 

How can we define the iterators?

An object or an array to be iterable, it needs to implement the iterable protocol, meaning that the object must have a property with a Symbol.iterator key. In the previous example, we have used this protocol.

//main.js

let mj = dances[Symbol.iterator]();

We have used dances array and to make it iterable, we have used Symbol.iterator protocol to make it iterable.

We can test the variable whether it is an array or an object that is iterable or not by the following code.

//main.js

function itemIterable(item) {
    return typeof item[Symbol.iterator] == "function";
}

In above example, when we pass the mj array to this itemIterable() function, we will get the following result.

//main.js

let dances = ['Robot', 'Hip-hop','break'];
let mj = dances[Symbol.iterator]();
function itemIterable(item) {
    return typeof item[Symbol.iterator] == "function";
}
let result = itemIterable(mj);
console.log(result);

Output

true

for...of loop

It creates a loop iterating over iterable objects like an array, object, map, set, weak set, string and its new feature of ES6.

Syntax

for (var of iterable) {
  // statement
}

varOn every iteration of the loop, a value of a different property is assigned to the variable.

iterableAn object whose properties are iterated.

//main.js

let dances = ['Robot', 'Hip-hop','break'];
for (let value of dances){
    console.log(value);
}

Output

Robot
Hip-hop
break
Iterators in Javascript
Iterators in Javascript

 

If we want to create an iterator then first take an object and then add Symbol.iterator protocol in it so it returns an interface in which we can call the next() method and then finally we get an object, which has 2 properties value and done.

Memorable Points

  1. Iterators are functions that provide an interface through which can call the method like next() and in return gives us an object.
  2. Iterators are created using the iterable protocol that allows the iterable object to customize their behavior. For example, arrays are not iterators in ES6
  3. An Iterator lets us iterate the content of an object at a given point of time.
  4. An Iterator creates Traversable Data Structures.
If you still have doubt then ask in the comment below, I am happy to help you out.

The post Iterators in Javascript appeared first on AppDividend.

]]>
https://appdividend.com/2017/04/16/iterators-in-javascript/feed/ 0
Pure Functions In Javascript https://appdividend.com/2017/04/10/pure-functions-in-javascript/ https://appdividend.com/2017/04/10/pure-functions-in-javascript/#respond Mon, 10 Apr 2017 22:09:46 +0000 http://localhost/final/?p=290 Pure Functions In Javascript

Hello, Developers.  In today’s AppDividend Tutorial, I have briefly described Pure Functions In Javascript. Pure functions in Javascript are kind of Functions where the return value is determined by its parameter passed at call time. Javascript is not a purely functional language; it treats functions as objects (first-class functions). If you provide some input parameter value to the function and […]

The post Pure Functions In Javascript appeared first on AppDividend.

]]>
Pure Functions In Javascript

Hello, Developers.  In today’s AppDividend Tutorial, I have briefly described Pure Functions In Javascript.

Pure functions in Javascript are kind of Functions where the return value is determined by its parameter passed at call time.

Javascript is not a purely functional language; it treats functions as objects (first-class functions).

If you provide some input parameter value to the function and it always returns the same result, then It’s Pure Functions in Javascript.

Pure Functions

Pure Functional Programming concept is derived from this two strict functional programming Language.

  1. Clojure
  2. Scala

Pure Functions strictly does not rely on particular Ajax call or any Database call. It simply takes a parameter and performs some calculation provides in function body and return it.

It solely depends upon the argument pass it into the functions call.

Pure Functions In Javascript
Pure Functions In Javascript

It only maps the input values to the output values.

You can call this programming style as a Procedural Programing because It is a sequence of operations performs on the input to that function.

The function can access only those variables that are pass to that function as a parameter.

A global variable or an instance of a class is not considered as a legitimate variable inside any Pure Functions.

The global scope of a variable is not used in the producing of a Pure Functions.

It’s set of instruction that behaves as a Mathematical Functions.

It’s a role-based function whose only task is to take an argument, perform some operations on that variable and then return it.

Advantages:

  1. You can always predict the result of a given function.
  2. Testing is always easy because It does not mutate the state of a variable outside of its lexical scope.
  3. Functional programming reduces the line of codes and almost get rid of a loop.

Examples:

 

//main.js

let pure = (y) => {
    let x = 10;
    x = x + y;
    return x;
};

let y = pure(3);
console.log(y); // 13

let z = pure(3);
console.log(z); // 13

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file

In above example, every time at call time of the function, when we pass the parameter as three then It will always give us 13 in return in all the circumstances. So it’s a Pure Javascript Function.

In JavaScript, simple variables like numbers, strings and booleans are immutable. However, data structures like objects and arrays are mutable because it is a collection of data.

//main.js

const numbers = [1, 2, 3];
numbers.forEach(x => console.log(x)); //1 2 3

Arrays and Objects can be mutated because It’s a non-primitive data type.

Above example simple print the value of an element in an array one by one so It’s a Pure Javascript Function.

Example #1

//main.js

let arr = [1, 2, 3, 4, 5, 6];

even = arr.filter(function (element) {
    return element%2 === 0;
});
console.log(even); //[2,4,6]

If you do not mutate an old state of an array, then It is also called Pure Functions.

In above example, Filter function just checks the condition and if it satisfies than It returns the new set of an array.

Example #2

//main.js

let dances = [
    {name: 'Krunal', type: 'Robot'},
    {name: 'Ankit', type: 'Salsa'},
    {name: 'Tom', type: 'Garba'},
    {name: 'Jerry', type: 'Belly'}
];
let collection = dances.filter((dance)=>{
   return  dance.type === 'Robot'
});
console.log(collection); // [object]

The post Pure Functions In Javascript appeared first on AppDividend.

]]>
https://appdividend.com/2017/04/10/pure-functions-in-javascript/feed/ 0
Beginner’s Guide To Setup React v15.4.2 Environment https://appdividend.com/2017/03/29/beginners-guide-to-setup-react-v15-4-2-environment/ https://appdividend.com/2017/03/29/beginners-guide-to-setup-react-v15-4-2-environment/#comments Wed, 29 Mar 2017 11:35:44 +0000 http://localhost/final/?p=65 Setup React Environment

Hello, Web Developers.  In today’s AppDividend Tutorial, I have briefly described Beginner’s Guide To Setup React Environment in our local machine. React.js is an open-source JavaScript framework for building user interfaces developed at Facebook. Airbnb, Instagram, Flipkart are using React.js for the frontend. So Let’s Get Started!! If you want to learn more about React and Redux then check out this React 16.6 […]

The post Beginner’s Guide To Setup React v15.4.2 Environment appeared first on AppDividend.

]]>
Setup React Environment

Hello, Web Developers.  In today’s AppDividend Tutorial, I have briefly described Beginner’s Guide To Setup React Environment in our local machine.

React.js is an open-source JavaScript framework for building user interfaces developed at Facebook.

Airbnb, Instagram, Flipkart are using React.js for the frontend.

So Let’s Get Started!!

If you want to learn more about React and Redux then check out this React 16.6 – The Complete Guide (incl. React Router & Redux) course.

I  am assuming that you have already install node.js in your machines.

Setup React Environment

Step 1: Create a project folder in your directory.

mkdir react-environment

Navigate to that folder.

cd react-env

Step 2: Create a package.json file to manage all the node dependencies.

For initialization of this file, type following command in your terminal.

npm init

So, your package.json file looks like this.

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {},
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Step 3: Install webpack and webpack-dev-server.

We need two things

  1. Webpack: to bundle all of our javascript files into one file and host that file on the server.
  2. Webpack Development Server: We need this server to recompile our main javascript file every time we change and provide us one server.

Install locally for our project type

npm install webpack webpack-dev-server --save-dev

Step 4: Create index.html file.

Create a new file in root folder called index.html

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React v15.4.2 ES6 Environment</title>
</head>
<body>
    <script type="text/javascript" src="bundle.js"></script>
</body>
</html>

Here we have included only one javascript file called bundle.js in our HTML page, which is bundled by Webpack.
Create a directory called app in the root folder.

In the app directory, create a new javascript file called app.js.

Write only one line of code in the main.js file.

// main.js

console.log('Inside app folder');

Step 5: Configure webpack.config.js file in a root directory.

In the webpack.config.js file, we need to export all the webpack settings by exporting javascript object.

//webpack.config.js

module.exports = {
    entry: ['./app/main.js'],
    output: {
        filename: 'bundle.js'
    }
};

Here we need some explanations right?

Basically, module.exports export an object, which describes our webpack configuration for our object.

The object contains two properties.

entry: – which represents our entry javascript file for the project. In our case It is  js6 > app > main.js

output: – the output bundled file, which we have to include in our main HTML file called bundle.js

Go to the package.json file and edit the following JSON property.

"scripts": {}

We add a new property  called “build” and value called “webpack-dev-server.”

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Go to the terminal in your root project folder and type following command.

npm run build

It will create a bundled javascript file called “bundle.js.”

Next, we need to configure Babel.js in our webpack environment.

Step 6: Install and set Babel dependencies.

npm install babel-core babel-loader babel-preset-es2015 --save-dev

It will update our package.json file.

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}

babel-core and babel-loader is the dependency, which transpile the ES6 code to ES5

babel-preset-es2015 let us use some advanced feature of ECMAScript in our web applications.

Update our webpack.config.js file.

webpack.config.js file looks like this.

//webpack.config.js

module.exports = {
    entry: './app/main.js',
    output: {
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        port: 3000
    }
};

Here we have added module object, which has loaders property.

It will accept an array of loader configuration, like which loader we want to use and which file we have to test with the extension .js and which file we need to exclude from transpiling from es6 to es5 like “node_modules” folder.

Also, I have added one optional attribute called devServer.

It includes the port number on which we need to host our app. by default webpack-dev-server provides port 8080.

But we can change it and put port 3000.

So now when you run again command

npm run buid

App will be running on http://localhost:3000/

Step 7: Install And Configure React and ReactDOM.

npm install --save react react-dom

We also need to use the package called “babel-preset-react” and “babel-preset-stage-3” to use latest ES6 features as well as we can write react code in ES6 syntax.

npm install --save-dev babel-preset-react babel-preset-stage-3

Your package.json file is updated and will look like this.

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "babel-preset-stage-3": "^6.22.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  }
}

We need to create one file in root directory called .babelrc

This file contains one object configuration which includes which Babel configuration of the array we are using.

{
  "presets": ["es2015", "react", "stage-3"]
}

Step 8: Create a component file App.js inside components folder.

Create one directory inside an app folder called components

In that create one file called App.js (react-environment > app > components > App.js)

//App.js

import React, { Component } from 'react';
export default class App extends Component {
    render(){
        return (
            <div>
                Hello From React v15.4.2
            </div>
        );
    }
}

Step 9: Import App.js file into main.js file.

We need to import this file into our main.js file.

//main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

ReactDOM.render(<App />, document.getElementById('app'));

Our final application directory structure looks like this.

Beginner's Guide To Setup React v15.4.2 Environment123

 

main.js  is the file, which will be transpile by Babel and bundled by webpack.

You can restart your server and type

npm run build

Open the browser and go to this URL:  http://localhost:3000/

“Hello From React v15.4.2.”

This code you can find in Github URL: https://github.com/KrunalLathiya/react-v15.2.4-environment

Now your React Application is running on your port 3000 with all ECMAScript’s Latest features.

Note:  If you find any error during this small setup,

  1. First, check your Node and NPM versions
  2. Check off your dependencies version by comparing package.json file with yours because you might end up with downloading another version of that particular dependencies.

If you have any questions, please ask in a comment below. I am happy to help you out.

The post Beginner’s Guide To Setup React v15.4.2 Environment appeared first on AppDividend.

]]>
https://appdividend.com/2017/03/29/beginners-guide-to-setup-react-v15-4-2-environment/feed/ 12
Beginner’s Guide To Setup ES6 Development Environment https://appdividend.com/2017/03/28/beginners-guide-to-setup-es6-development-environment/ https://appdividend.com/2017/03/28/beginners-guide-to-setup-es6-development-environment/#comments Tue, 28 Mar 2017 15:55:03 +0000 http://localhost/final/?p=14 Beginner’s Guide To Setup ES6 Development Environment

Hello, Web Programmers. Beginner’s Guide To Setup  ES6 Development Environment. To setup es6 development environment in local machine, we need to understand two tools. Babel Webpack Babel Babel is a transpiler that just converts the code from ES6 to ES5 to support all modern browsers. For more information, please visit this official BabelJS website. https://babeljs.io/ Webpack Webpack is module […]

The post Beginner’s Guide To Setup ES6 Development Environment appeared first on AppDividend.

]]>
Beginner’s Guide To Setup ES6 Development Environment

Hello, Web Programmers. Beginner’s Guide To Setup  ES6 Development Environment.

To setup es6 development environment in local machine, we need to understand two tools.

  1. Babel
  2. Webpack

Babel

Babel is a transpiler that just converts the code from ES6 to ES5 to support all modern browsers.

For more information, please visit this official BabelJS website. https://babeljs.io/

Webpack

Webpack is module bundle for modern javascript web applications. Using webpack, we do not host multiple javascript files. We just host one file for an entire web application.

Let us take an example, for our project we only include only one javascript file.

For More information, please visit this official Webpack website. https://webpack.github.io/docs/

If you are taking this demo, then have already installed the Node.js in your machines.

Setup ES6 Development Environment

Step 1: Create a project folder.

Create an empty project folder.

mkdir js6

Navigate to that directory by typing,




cd js6

Step 2: Create a package.json file.

We need to create a JSON file called package.json

npm init

Your package.json file looks like this.

{
  "name": "js6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {},
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Step 3: Install webpack globally and locally.

We need to install webpack globally.

For Windows, open a command prompt in administrator mode.

npm install -g webpack

For Linux or Mac.

sudo npm install -g webpack

We need to install webpack locally.

npm install webpack --save-dev

Here, we have used –save-dev flag.

The reason behind is that we need to install this dependency for the development setup, not for production setup.

Step 4: Include bundled file in the HTML page.

Create an index.html file in root folder.

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ES2015 Environment</title>
</head>
<body>
</body>
</html>

Now, include a script tag in your body tag.

<!-- index.html -->

<script src="bundle.js" type="text/javascript"></script>

Create a new directory called app in the root folder.

In that create a javascript file called main.js

For testing write only one line of code in main.js file

//main.js

console.log('Inside main.js');

Step 5: Create a webpack configuration file.

Now, create a webpack configuration file in a root folder named as webpack.config.js

In this file, we need to export all the webpack settings by exporting javascript object.

//webpack.config.js

module.exports = {
    entry: ['./app/main.js'],
    output: {
        filename: 'bundle.js'
    }
};

Here we need some explanations right?

module.exports : It is an object that describes our webpack configuration.

The object contains two properties, which is very basic configuration.

entry: – which represents our entry javascript file for the project. In our case It is  js6 > app > main.js

output: – the output bundled file, which we have included in our main HTML file called bundle.js

We need to update package.json file’s scripts property.

"scripts": {}

We add new properties called “build” and value called “webpack“.

{
  "name": "js6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC"
}

Run the build command again.

npm run build

It will create a bundled file names as “bundle.js“.

Now open an index.html file in a browser, and you will see in the chrome developer tools,  inside console panel, there is logging by saying

Hello from main.js.”

Cool!!, we have successfully bundled out main.js file into the bundle.js file, and if you open that file, we can see ES5 code.

Now, change the content of the main.js file and refresh the page.

Console panel output will remain the same.

To overcome this problem.

We need to a package called “webpack-dev-server“.

Step 6: Install webpack development server.

To get webpack-dev-server globally on Linux and Mac.

sudo npm install -g webback-dev-server

To get webpack locally

npm install --save-dev webpack-dev-server

We need to update the package.json file.

"build": "webpack-dev-server"

That’s it!! Now start your webpack by typing

npm run build

Now analyze the terminal, It says that your project will serve on http://localhost:8080

You will see the console panel result that we will get the same thing.

Hello from main.js

Now change the main file like “Hello from bundle.js“.

It will recompile automatically, and you can see the changes are reflecting in the browser.

Step 7: Use Babel in our development environment.

Now, we need to configure Babel.js in our webpack environment.

Download some dependencies from NPM.

npm install babel-core babel-loader babel-preset-es2015 --save-dev

It will update our package.json file.

{
  "name": "js6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "KRUNAL LATHIYA",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}

 

babel-core and babel-loader is the dependency, which transpiles the es6 code to es5

babel-preset-es2015 let us use some advanced feature of ECMA Script in our web applications.

Now, we have to update our webpack.config.js file.

Step 8 : Edit webpack.config.js file.

Updated webpack.config.js file looks like this.

//webpack.config.js

module.exports = {
    entry: './app/main.js',
    output: {
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        port: 3000
    }
};

Here we have added module object, which has loaders property.

It will accept an array of loader configuration, like which loader we want to use and which file we have to test with the extension .js and which file we need to exclude from transpiling from es6 to es5 like “node_modules” folder.

I  have added one optional attribute called devServer.

It includes a port number on which we need to host our app. by default webpack-dev-server provides port 8080.

We can change it and put port 3000.

Please close the server and type below in terminal.

npm run buid



An App will be running on http://localhost:3000/

Our final directory structure will look like this.

Beginner’s Guide To Setup ES6 Development Environment

Step 9: Write ES6 code into our main.js file.

Now test one ECMA Script Feature called Arrow Function

You will have to open a main.js file and write below code.

Beginner’s Guide To Setup ES6 Development Environment

//main.js

let app = (name) => {
    console.log(`hello from ${name}`);
}
app('Krunal');

You will see in the browser that, it has been updated and in the console, we can see “hello from Krunal.”

We have built an environment to write ES6 code, and It will be compatible with today’s browser.

This code you can find in my GitHub URL: https://github.com/KrunalLathiya/es6-environment

Possible Errors

  1. First, check your Node and NPM versions
  2. You need to check all of your dependencies version by comparing package.json file to avoid version conflicting.

If you have any questions, please ask in a comment below. I am happy to help you out.

Finally, we have achieved setup es6 development environment in the local machine.

The post Beginner’s Guide To Setup ES6 Development Environment appeared first on AppDividend.

]]>
https://appdividend.com/2017/03/28/beginners-guide-to-setup-es6-development-environment/feed/ 13