ブラウザにまだサポートされていないようなJSの次世代標準機能をブラウザで使えるようにするNode.jsトランスパイラ
ES6, ES7など(ECMAScript)
Bableを使う際に書くのはAltJSではなく、純粋なJavaScript
Bable ES6の構文サポート
– Class, Template Strings, Arrow Function, Default Parameter, Rest Parameter, Property Literals, Modules
class Code { constructor(item){ this.item = item; } showItem(){ console.log(`you are buying ${this.item}`); } } class Sec extends Code { constructor(item = 'コロプラ'){ super(item); } } var app = new Sec(); app.showItem();
[vagrant@localhost front]$ node entry.js
you are buying コロプラ
では、早速Babelをインストールしましょう。
$ npm install -g babel-cli
$ babel entry.js –out-file output.js
あれ、全然変わってない?
presetをインストールして、.babelrcを書く必要がある??
$ npm install –save-dev babel-preset-env
.babelrc
{ "presets": ["env"] }
再度実行
$ babel entry.js –out-file output.js
output.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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Code = function () { function Code(item) { _classCallCheck(this, Code); this.item = item; } _createClass(Code, [{ key: 'showItem', value: function showItem() { console.log('you are buying ' + this.item); } }]); return Code; }(); var Sec = function (_Code) { _inherits(Sec, _Code); function Sec() { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'コロプラ'; _classCallCheck(this, Sec); return _possibleConstructorReturn(this, (Sec.__proto__ || Object.getPrototypeOf(Sec)).call(this, item)); } return Sec; }(Code); var app = new Sec(); app.showItem();
なるほど、OK!
ES5への変換は、babel-preset-envが必要ってことね。
そんで、これ、webpackとどう連携するの?