BabelJS - Examples

We will use ES6 features and create a simple project. Babeljs will be used to compile the code to ES5. The project will have a set of images, which will autoslide after a fixed number of seconds. We will use ES6 class to work on it. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name.
We will use gulp to build the project. To start with, we will create the project setup as shown below
npm init

We have created a folder called babelexample. Further, we will install gulp and other required dependencies.
npm install gulp --save-dev
npm install gulp-babel --save-dev
npm install gulp-connect --save-dev
npm install babel-preset-env --save-dev

Here is the Package.json after installation −
We will add the Preset environment details to .babelrc file as follows −
Since we need the gulp task to build the final file, we will create gulpfile.js with the task that we need
gulpfile.js
var gulp = require('gulp');
var babel = require('gulp-babel');
var connect = require("gulp-connect");
gulp.task('build', () => {
   gulp.src('src/./*.js')
      .pipe(babel())
      .pipe(gulp.dest('./dev'))
});
gulp.task('watch', () => {
   gulp.watch('./*.js', ['build']);
});

gulp.task("connect", function () {
   connect.server({
      root: ".",
      livereload: true
   });
});

gulp.task('start', ['build', 'watch', 'connect']);
We have created three tasks in gulp, [‘build’,’watch’,’connect’]. All the js files available in src folder will be converted to es5 using babel as follows
gulp.task('build', () => {
   gulp.src('src/./*.js')
      .pipe(babel())
      .pipe(gulp.dest('./dev'))
});
The final changes are stored in the dev folder. Babel uses presets details from .babelrc. In case you want to change to some other preset, you can change the details in .babelrc file.
Now, we will create a .js file in src folder using es6 JavaScript and run gulp start command to execute the changes.
The project structure is as follows −
src/slidingimage.js
class SlidingImage {
   constructor(width, height, imgcounter, timer) {
      this.counter = 0;
      this.imagecontainerwidth = width;
      this.imagecontainerheight = height;
      this.slidercounter = imgcounter;
      this.slidetimer = timer;
      this.startindex = 1;
      this.css = this.applycss();
      this.maincontainer = this.createContainter();
      this.childcontainer = this.imagecontainer();
      this.autoslide();
   }

   createContainter() {
      let maindiv = document.createElement('div');
      maindiv.id = "maincontainer";
      maindiv.class = "maincontainer";
      document.body.appendChild(maindiv);
      return maindiv;
   }

   applycss() {
      let slidercss = ".maincontainer{ position : relative; margin :auto;}.left, 
         .right {
            cursor: pointer; position: absolute;" +
            "top: 50%; width: auto; padding: 16px; margin-top: -22px; color: white; font-weight: bold; " +
            "font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0;
         }.right { right: 0; border-radius: 3px 0 0 3px;}" +
         ".left:hover, .right:hover { background-color: rgba(0,0,0,0.8);}";
      let style = document.createElement('style');
      style.id = "slidercss";
      style.type = "text/css";
      document.getElementsByTagName("head")[0].appendChild(style);
      let styleall = style;
      if (styleall.styleSheet) {
      styleall.styleSheet.cssText = slidercss;
      } else {
         let text = document.createTextNode(slidercss);
         style.appendChild(text);
      }
   }

   imagecontainer() {
      let childdiv = [];
      let imgcont = [];
      for (let a = 1; a >= this.slidercounter; a++) {
         childdiv[a] = document.createElement('div');
         childdiv[a].id = "childdiv" + a;
         childdiv[a].style.width = this.imagecontainerwidth + "px";
         childdiv[a].style.height = this.imagecontainerheight + "px";
         if (a > 1) {
            childdiv[a].style.display = "none";
         }
         imgcont[a] = document.createElement('img');
         imgcont[a].src = "src/img/img" + a + ".jpg";
         imgcont[a].style.width = "100%";
         imgcont[a].style.height = "100%";
         childdiv[a].appendChild(imgcont[a]);
         this.maincontainer.appendChild(childdiv[a]);
      }
   }

   autoslide() {
      console.log(this.startindex);
      let previousimg = this.startindex;
      this.startindex++;
      if (this.startindex > 5) {
         this.startindex = 1;
      }
      setTimeout(() => {
         document.getElementById("childdiv" + this.startindex).style.display = "";
         document.getElementById("childdiv" + previousimg).style.display = "none";
         this.autoslide();
      }, this.slidetimer);
   }
}

let a = new SlidingImage(300, 250, 5, 5000);    
We will create img/ folder in src/ as we need images to be displayed; these images are to rotate every 5 seconds.The dev/ folder will store the compiled code. Run the gulp start to build the final file.
The final project structure is as shown below −
In slidingimage.js, we have created a class called SlidingImage, which has methods like createcontainer, imagecontainer, and autoslide, which creates the main container and adds images to it. The autoslide method helps in changing the image after the specified time interval.
let a = new SlidingImage(300, 250, 5, 5000);
At this stage, the class is called. We will pass width, height, number of images and number of seconds to rotate the image.
gulp start

dev/slidingimage.js
"use strict";

var _createClass = function () {
   function defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
         var descriptor = props[i]; 
         descriptor.enumerable = descriptor.enumerable || false; 
         descriptor.configurable = true; 
         if ("value" in descriptor) descriptor.writable = true; 
         Object.defineProperty(target, descriptor.key, descriptor); 
      } 
   }
   return function (Constructor, protoProps, staticProps) {
      if (protoProps) defineProperties(Constructor.prototype, protoProps);
      if (staticProps) defineProperties(Constructor, staticProps); return Constructor;
   };
}();

function _classCallCheck(instance, Constructor) {
   if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function"); 
   } 
}

var SlidingImage = function () {
   function SlidingImage(width, height, imgcounter, timer) {
      _classCallCheck(this, SlidingImage);
      this.counter = 0;
      this.imagecontainerwidth = width;
      this.imagecontainerheight = height;
      this.slidercounter = imgcounter;
      this.slidetimer = timer;
      this.startindex = 1;
      this.css = this.applycss();
      this.maincontainer = this.createContainter();
      this.childcontainer = this.imagecontainer();
      this.autoslide();
   }
   _createClass(SlidingImage, [{
      key: "createContainter",
      value: function createContainter() {
         var maindiv = document.createElement('div');
         maindiv.id = "maincontainer";
         maindiv.class = "maincontainer";
         document.body.appendChild(maindiv);
         return maindiv;
      }
   }, {
      key: "applycss",
      value: function applycss() {
         var slidercss = ".maincontainer{ position : relative; margin :auto;}.left, .right {
            cursor: pointer; position: absolute;" + "top: 50%;
            width: auto;
            padding: 16px;
            margin-top: -22px;
            color: white;
            font-weight: bold;
            " + "font-size: 18px;
            transition: 0.6s ease;
            border-radius: 0 3px 3px 0;
         }
         .right { right: 0; border-radius: 3px 0 0 3px;}" +
            ".left:hover, .right:hover { background-color: rgba(0,0,0,0.8);}";
         var style = document.createElement('style');
         style.id = "slidercss";
         style.type = "text/css";
         document.getElementsByTagName("head")[0].appendChild(style);
         var styleall = style;
         if (styleall.styleSheet) {
            styleall.styleSheet.cssText = slidercss;
         } else {
            var text = document.createTextNode(slidercss);
            style.appendChild(text);
         }
      }
   }, {
      key: "imagecontainer",
      value: function imagecontainer() {
      var childdiv = [];
      var imgcont = [];
      for (var _a = 1; _a <= this.slidercounter; _a++) {
         childdiv[_a] = document.createElement('div');
         childdiv[_a].id = "childdiv" + _a;
         childdiv[_a].style.width = this.imagecontainerwidth + "px";
         childdiv[_a].style.height = this.imagecontainerheight + "px";
         if (_a > 1) {
            childdiv[_a].style.display = "none";
         }
         imgcont[_a] = document.createElement('img');
         imgcont[_a].src = "src/img/img" + _a + ".jpg";
         imgcont[_a].style.width = "100%";
         imgcont[_a].style.height = "100%";
         childdiv[_a].appendChild(imgcont[_a]);
         this.maincontainer.appendChild(childdiv[_a]);
         }
      }
   }, {
      key: "autoslide",
      value: function autoslide() {
         var _this = this;

         console.log(this.startindex);
         var previousimg = this.startindex;
         this.startindex++;
         if (this.startindex > 5) {
            this.startindex = 1;
         }
         setTimeout(function () {
            document.getElementById("childdiv" + _this.startindex).style.display = "";
            document.getElementById("childdiv" + previousimg).style.display = "none";
            _this.autoslide();
         }, this.slidetimer);
      }
   }]);
   return SlidingImage;
}();

var a = new SlidingImage(300, 250, 5, 5000);
We will test the line of code in browser as shown below −
index.html
<html>
   <head></head>
   <body>
      <script type="text/javascript" src="dev/slidingimage.js"></script>
      <h1>Sliding Image Demo</h1>
   </body>
</html>
We have used the compiled file from the dev folder in index.html. The command gulp start starts the server where we can test the output.
The code compiled works fine in all browsers.
 Print
 Add Notes
 Bookmark this page