静下心来的个人专栏
上一篇

BabelJS - 使用 Babel 6 进行项目设置

广告
选中文字可对指定文章内容进行评论啦,→和←可快速切换按钮,绿色背景文字可以点击查看评论额。
大纲

BabelJS - 使用 Babel 6 进行项目设置

在本章中,我们将看到如何在我们的项目中使用 babeljs。我们将使用 nodejs 创建一个项目,并使用 http 本地服务器来测试我们的项目。

项目package.json如下

{
  "name": "babelproject",
  "version": "1.0.0",
  "description": "babel use and study",
  "main": "index.js",
  "scripts": {
    "babel": "babel",
    "build": "lite-server",
    "babel-es6": "babel --preset es2015 src/index.js -o script/build.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "lite-server": "^2.6.1"
  }
}

index.js

class Student {
   constructor(fname, lname, age, address) {
      this.fname = fname;
      this.lname = lname;
      this.age = age;
      this.address = address;
   }

   get fullname() {
      return this.fname +"-"+this.lname;
   }
}

运行如下代码:

npm run babel-es6

生成的代码如下:

"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 Student = function () {
   function Student(fname, lname, age, address) {
      _classCallCheck(this, Student);

      this.fname = fname;
      this.lname = lname;
      this.age = age;
      this.address = address;
   }

   _createClass(Student, [{
      key: "fullname",
      get: function get() {
         return this.fname + "-" + this.lname;
      }
   }]);

   return Student;
}();

新建一个html文件如下:

<html>
   <head></head>
   <body>
      <script type="text/javascript" src="script/build.js?a=11"></script>
      <h1 id="displayname"></h1>
      <script type="text/javascript">
         var a = new Student("Siya", "Kapoor", "15", "Mumbai");
         var studentdet = a.fullname;
         document.getElementById("displayname").innerHTML = studentdet;
      </script>
   </body>
</html>

运行

npm run build

打开浏览器可以看到:

可以看见,我们创建了一个简单的将es6的语法转化成es2015的语法,保证了这个小的项目在大部分浏览器能够正常运行。

版权声明:著作权归作者所有。

X

欢迎加群学习交流

联系我们