BabelJS - 示例



我们将使用 ES6 特性并创建一个简单的项目。Babeljs 将用于将代码编译为 ES5。该项目将包含一组图像,这些图像将在固定的秒数后自动轮播。我们将使用 ES6 类来实现它。我们在项目设置中使用了 babel 6。如果您想切换到 babel 7,请使用@babel/babel-package-name安装 babel 的所需包。

自动轮播图片

我们将使用 gulp 来构建项目。首先,我们将创建如下所示的项目设置

命令

npm init

Auto Slide Images

我们创建了一个名为 babelexample 的文件夹。接下来,我们将安装 gulp 和其他必要的依赖项。

命令

npm install gulp --save-dev
npm install gulp-babel --save-dev
npm install gulp-connect --save-dev
npm install babel-preset-env --save-dev

安装后,Package.json 如下所示:

babelexample

我们将预设环境详细信息添加到.babelrc 文件中,如下所示:

Babelrc Environment Details

由于我们需要 gulp 任务来构建最终文件,我们将创建包含所需任务的 gulpfile.js

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']);

我们在 gulp 中创建了三个任务,['build','watch','connect']。src 文件夹中所有可用的 js 文件将使用 babel 转换为 es5,如下所示:

gulp.task('build', () => {
   gulp.src('src/./*.js')
      .pipe(babel())
      .pipe(gulp.dest('./dev'))
});

最终更改存储在 dev 文件夹中。Babel 使用 .babelrc 中的预设详细信息。如果您想更改为其他预设,您可以更改 .babelrc 文件中的详细信息。

现在,我们将使用 es6 JavaScript 在 src 文件夹中创建一个.js 文件,并运行gulp start命令来执行更改。

项目结构如下:

Babel Project Structure

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);    

我们将创建src/中的img/文件夹,因为我们需要显示图像;这些图像每 5 秒旋转一次。dev/文件夹将存储编译后的代码。运行gulp start来构建最终文件。

最终项目结构如下所示:

Final Project Structure

slidingimage.js中,我们创建了一个名为SlidingImage的类,它具有诸如createcontainer、imagecontainer和autoslide等方法,这些方法创建主容器并将图像添加到其中。autoslide方法有助于在指定的时间间隔后更改图像。

let a = new SlidingImage(300, 250, 5, 5000);

在此阶段,调用该类。我们将传递宽度、高度、图像数量和旋转图像的秒数

命令

gulp start

Rotate Image

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);

我们将在浏览器中测试代码行,如下所示:

index.html

<html>
   <head></head>
   <body>
      <script type="text/javascript" src="dev/slidingimage.js"></script>
      <h1>Sliding Image Demo</h1>
   </body>
</html>

我们在index.html中使用了来自 dev 文件夹的编译文件。命令gulp start启动服务器,我们可以在其中测试输出。

在 Chrome 中

Sliding Image Chrome

在 Firefox 中

Sliding Image Firefox

在 Internet Explorer 中

sliding Image IE

编译后的代码在所有浏览器中都能正常工作。

广告