Learn Es6 part#4 Understand Class , Costructor and use combine webpack with babel

in utopian-io •  6 years ago  (edited)

Repository

https://github.com/babel/babel

What Will I Learn?

  • Understand Class
  • Use constructor()
  • Use webpack and combine it with babel
  • Export and import

Requirements

  • Basic Javascript and JS es6
  • Install node.js

Resources

Difficulty

Basic

Tutorial Content

We will continue the tutorial series from javascript es6 we have learned a lot about the syntax of es6, you can see it in the curriculum at the end of this tutorial. please follow in advance every step because this tutorial may be related to the previous tutorial. In this tutorial, I will discuss Class on es6 javascript and we will get acquainted with the web pack and how to use it. So we just start the tutorial this time.

Class in javascript es6

One of the most interesting features, in my opinion, is Class. If in javascript we usually can't use classes but in javascript es5 and es6 start introducing the use of classes in javascript. Of course, this makes it easier for us to write a function and allow us to apply the OOP concept to javascript. for those of you who are familiar with the OOP concept, it might not be difficult to learn Class on javascript. We can create classes in the following way.

Create a class

//Class
class groups{
    ....
}

We can easily create a class with the class keyword with the class name, class groups{}. After making a class we can call or create an instance of that class in the following way:

Create an instance class

new groups()

We can create an instance with the new keyword and its class name, in the class we can use the constructor (){} to run a function or certain things when the class is first called. we can see examples like the following.

Constructor

Same as in other programming languages the constructor is the function that will first run when the class is called. for example, we can see it below.

//Class
class groups{
    constructor(group){
        this.groupName = group
    }
}
let data  = new groups("Tutorial category")
console.log(data)
  • In the constructor we can pass parameters to be used when the function is called constructor (group) {} and we can save it to a global variable with the this.groupName.

  • to call the class we can use the keyword new classname () and because in the class using a constructor that has parameters, then when calling the class we must pass parameters like this new groups("Tutorial category"). If we run the code above then we will see the results as shown below.

Screenshot_2.png

  • Static methods

For those of you who are familiar with OOP(Object-oriented programming). You are certainly familiar with the concept of static methods in the class. You can also implement it in this es6 javascript. Here's how to use it.

//Static methods
class groups{
    constructor(group){
        this.groupName = group
    }
    static staticFunc(){
        return "This from Static methods"
    }
}
console.log(groups.staticFunc())
  • We can use static keywords to create static functions. The function above is staticFunc() which will ``return "This from Static methods"```.
  • static function difference is that we don't need to initialize the class we want to use like this let data = new groups("Tutorial category"), but we can directly call it by call the name of the class and then the name function like this groups.staticFunc(). We can see the results as shown below.

Screenshot_3.png

Webpack

This time we will get acquainted with the bundle web pack module or better known as webpack webpack is responsible for combining static files like css, javascript, image files. to use a web pack we must first install it as follows.

  • Install webpack

We can install webpack with NPM and install it globally as follows:
NPM:
npm install -g webpack
Screenshot_4.png

  • Use webpack

After we have installed the webpack we can now configure it before using it. The configuration will be simple, we only need to create a webpack.config.js file and in the file, we will define input files and output files as we do in Babel.

Webpack.config.js

module.exports = {
    entry  : './src/index.js',
    output : {
        filename : 'dist/index.js'
    }
}
  • entry This is the key that contains our input file, the file that we will bundle is in the directory src/index.js
  • output This is the key that contains the file directory that will save the results of our bundle. we will put it in the key filename : 'dist/index.js' of the object output{}.

  • Run webpack

We will run the webpack in our folder. we can use the command line to run it with the command webpack by running the webpack we automatically compile the file in /src/index.js and save it in the/dist/index.js file.

  • Combine Babel and Webpack

We need to know Babel is responsible for changing the syntax of es6 into javascript es5 or normal javascript. So that it can be used in all current browser versions. The webpack is responsible for downloading files that are input and saving them to the output file. Therefore we will combine Babel and Webpack. to combine it we need an extra plugin that is babel-loader, webpack plugin for Babel. We can install via NPM as follows.

Npm:
npm install babel-loader --save-dev

Screenshot_5.png

After we install the babel-loader we now need to add a module to webpack.config.js, like the example given.


module.exports = {
    entry  : './src/index.js',
    output : {
        filename : 'dist/index.js'
    }
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        }
      ]
    }
}

We will test it using a simple code in index.js and then compile the file with the webpack

const category = "Tutorials"
  console.log(category)

we will see the results of the webpack compile as follows

ezgif.com-video-to-gif.gif
The results above are compiled form webpack, we combine between babel and webpack.

  • Export and Import

We will discuss the export and import functions, as the name implies we can separate our javascript files. so now we can separate our javascript files into several files but we don't load them in HTML files. later the javascript file that we split will be merged into one main javascript file. Well, by doing that, we can use export and import. because not all browsers have not supported this method, that's why we use the webpack as a module bundler.

  • How to use ?

I will make an example like the following, we will create a folder that is the app folder and then I will create a data.js file which we will give an example block code.

app/data.js

export

let name = {
    myname : "millea duski"
}
//export the variable of name
export {name}



Index.js
import

import {name} from './app/data' //import the file data.js
console.log(name)

You can add variables that you will export or import by giving commas (,) like this export {var1, var2, var3}as well as import {var1, var2, var3}.


Use helper

It might not be a problem if we import only a few files, but it will be a bit messy and complicated. If we have to import one by one when our code needs to import many files. for that, we will create a file helper to bridge data imports. to create a helper file we can create an app/index.js file. later the index.js file will import all the files that are outside it. for example like the following.

app/index.js as helper

import * from './data'    //we can import all in member.js file
import * from './anotherFile1'
import * from './anotherFile2'

The code above means that the app/index.js file will import everything in the** app/member.js** file. we can use this method to import other file files like this import * from './anotherFile1' it just for example. Then in the index.js file that we can import all outside of the app/index.js file.

Index.js

import * as app from './app
  • We can import index files simply and we can create alias names import * as app, such as the code above, the app and then because the file name we import is index.js we no longer need to write like this app/index.js because all files automatically start from index.js.

We have learned several things in es6 javascript, I hope you can explore more about es6. thank you for following this tutorial, hopefully, helps those of you who want to try the frontend framework, you should be familiar with es6 javascript.

Curriculum

Learn Es6#1 Intro Setup babel and understand var,let,const
Learn Es6#2 Arrow Function, Default parameter, rest and spread
Learn Es6#3 String literal and destructuring object

Proof of work done

https://github.com/milleaduski/learnEs6

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for your contribution.

  • Excellent and simple to understand tutorial. We look forward to reviewing your next tutorial with more complex features.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin!

So far this week you've reviewed 5 contributions. Keep up the good work!

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!