モジュールを使用しない場合:
モジュール (インポート/エクスポート) を使用しない場合は、コードを ES5 にトランスパイルし、それらの ES5 ファイルを html に含めることができます。例:
// ES6 - index.js
// arrow function
var result = [1, 2, 3].map(n => n * 2);
console.log(result);
// enhanced object literal
var project = "helloWorld";
var obj = {
// Shorthand for ‘project: project’
project,
// Methods
printProject() {
console.log(this.project);
},
[ "prop_" + (() => 42)() ]: 42
};
console.log(obj.printProject());
console.log(obj);
es5 へのトランスパイル:babel index.js > es5.js
にindex.html
、<script src="es5.js"></script>
コンソールに次を出力します。
[2,4,6]
helloWorld
{"project":"helloWorld","prop_42":42}
モジュールの使用: モジュールを使用している場合 ( と の場合lib.js
) main.js
、コードを ES5 に変換した後、それらもバンドルする必要があります (AMD/CommonJS/Modules からブラウザが理解できるコードに)。これは、gulp、 webpack 、browserifyなどのさまざまなビルド システムで実行できます。ここでは例として browserify を使用します。
私のフォルダ構造が次のようになっているとします。
es6
|- src
|- lib.js
|- main.js
|- compiled
|- index.html
babel を実行して、ファイル/src
を/compiled
フォルダーにトランスパイルします: babel src --out-dir compiled
.
これで、コンパイル済みフォルダーに ES5 コードができました。cmd ラインに browserify をインストールし、コンパイル済みフォルダーに main.js (エントリ ポイント) をバンドルします。
~/es6 » npm install --global browserify
~/es6 » browserify ./compiled/main.js -o ./bundle.js
これでbundle.js
、次のようになります。
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
exports.square = square;
exports.diag = diag;
var sqrt = exports.sqrt = Math.sqrt;
function square(x) {
return x * x;
}
function diag(x, y) {
return sqrt(square(x) + square(y));
}
Object.defineProperty(exports, "__esModule", {
value: true
});
},{}],2:[function(require,module,exports){
"use strict";
var _lib = require("./lib");
var square = _lib.square;
var diag = _lib.diag;
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
},{"./lib":1}]},{},[2]);
次に、index.html で:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ECMAScript 6</title>
<script src="./bundle.js"></script>
</head>
<body>
</body>
</html>
次に、単に開くindex.html
と、コンソールに次のように表示されます。
121 bundle.js:27
5 bundle.js:28